[英]how can i change this to replace the 404 page error with a html page?
我必须使用我的html文件中的自定义页面更改404错误页面。 我写了这段代码,但它不起作用,和/或我不知道如何使用它。
public static void main(String[] args) throws Exception {
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/rac");
Server jettyServer = new Server(8080);
context.setWelcomeFiles(new String[] { "./src/main/resources/index.html" });
ErrorPageErrorHandler errorHandler = new ErrorPageErrorHandler();
errorHandler.addErrorPage(HttpStatus.NOT_FOUND_404, "./src/main/resources/error.html");
context.setErrorHandler(errorHandler);
// HTML
DefaultServlet defaultServlet = new DefaultServlet();
ServletHolder holderPwd = new ServletHolder("default", defaultServlet);
holderPwd.setInitParameter("resourceBase", "./src/main/resources/index.html");
context.addServlet(holderPwd, "/*");
// SERVICES
ServletHolder jerseyServlet = context.addServlet(org.glassfish.jersey.servlet.ServletContainer.class,
"/ajax/*");
jerseyServlet.setInitOrder(0);
jerseyServlet.setInitParameter("jersey.config.server.provider.classnames",
DiskServiceWS.class.getCanonicalName() + "," + RamServiceWS.class.getCanonicalName() + ","
+ CpuServiceWS.class.getCanonicalName());
jettyServer.setHandler(context);
try {
jettyServer.start();
jettyServer.join();
} finally {
jettyServer.destroy();
}
}
您尚未说明您遇到的404错误。
如果来自Jetty本身的404(不是上下文的一部分),则由Server
级别的ErrorHandler
。 (例如在您的方案中对http://<machine>/foo/bar
的GET请求,因为“/ foo”不是“/ wac”上下文的一部分)
如果404中的错误会回流到ServletContextHandler
,那么现有的ErrorPageErrorHandler
大多是正确的。
addErrorPage
上的第二个参数是URL路径(相对于您声明的Base Resource),而不是文件系统路径。
示例(假设可以通过Web GET请求访问/error.html
):
ErrorPageErrorHandler errorHandler = new ErrorPageErrorHandler();
errorHandler.addErrorPage(HttpStatus.NOT_FOUND_404, "/error.html");
context.setErrorHandler(errorHandler);
注意:URL路径可以指向Servlet(您的,jsp,jersey端点等等),如果您愿意,它不必是HTML。
如果404来自JAX-RS / Jersey请求,那么JAX-RS / Jersey中的特定处理将根据传入的请求详细信息生成有效的404错误响应。
一个示例是请求JSON资源的REST客户端,而Jersey生成带有JSON主体的404响应,指示错误详细信息。
其他说明......
DefaultServlet defaultServlet = new DefaultServlet();
ServletHolder holderPwd = new ServletHolder("default", defaultServlet);
holderPwd.setInitParameter("resourceBase", "./src/main/resources/index.html");
不要在DefaultServlet
上声明resourceBase
,在ServletContextHandler
上声明它。
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/rac");
context.setBaseResource(Resource.newResource("/path/to/my/base/directory"));
此外, resourceBase
是完全限定的目录路径(或URI),从不是文件或相对路径。
setWelcomeFiles
是传入的GET请求是目录资源时要使用的文件名或路径相对URL位置。
例:
context.setWelcomeFiles(new String[] { "index.html", "welcome.html", "index.jsp" });
因此,请求http://<machine>/wac/
将导致实际提供http://<machine>/wac/index.html
(如果存在)。
这也适用于深层目录请求,例如http://<machine>/wac/app/deps/scripts/jquery/
将导致提供http://<machine>/wac/app/deps/scripts/jquery/index.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.