谁能告诉我如何查看我的自定义 404 页面。我用谷歌搜索并尝试实现 ExceptionMapper<RuntimeException>
但这并没有完全奏效。我用的是0.8.1版本
我的异常映射器:
public class RuntimeExceptionMapper implements ExceptionMapper<NotFoundException> {
@Override
public Response toResponse(NotFoundException exception) {
Response defaultResponse = Response.status(Status.OK)
.entity(JsonUtils.getErrorJson("default response"))
.build();
return defaultResponse;
}
}
这只适用于不正确的 API,不适用于资源调用
我的设置:
@Override
public void initialize(Bootstrap<WebConfiguration> bootstrap) {
bootstrap.addBundle(new AssetsBundle("/webapp", "/", "index.html"));
}
@Override
public void run(WebConfiguration configuration, Environment environment) throws Exception {
environment.jersey().register(RuntimeExceptionMapper.class);
((AbstractServerFactory) configuration.getServerFactory()).setJerseyRootPath("/api/*");
// Registering Resources
environment.jersey().register(new AuditResource(auditDao));
....
}
现在,
http://localhost:8080/api/rubish
通过重写的 ExceptionMapper 方法
http://localhost:8080/rubish.html
导致默认 404 页面
我如何设置以便每当请求未知页面时 dropwizard 将显示自定义 404 页面
我引用了 this异常映射器的链接
最佳答案
要为任何错误配置自定义错误页面,您可以在您的应用程序中配置一个 ErrorPageErrorHandler,如下所示:
@Override
public void run(final MonolithConfiguration config,
final Environment env) {
ErrorPageErrorHandler eph = new ErrorPageErrorHandler();
eph.addErrorPage(404, "/error/404");
env.getApplicationContext().setErrorHandler(eph);
}
然后像这样创建一个资源:
@Path("/error")
public class ErrorResource {
@GET
@Path("404")
@Produces(MediaType.TEXT_HTML)
public Response error404() {
return Response.status(Response.Status.NOT_FOUND)
.entity("<html><body>Error 404 requesting resource.</body></html>")
.build();
}
以防万一您需要它,这里还有 ErrorPageErrorHandler 的导入:
import org.eclipse.jetty.servlet.ErrorPageErrorHandler;
关于java - 如何在 Dropwizard 中查看自定义 404 页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35460345/