如果没有找到内容/服务,是否可以配置ErrorPageErrorHandler重定向到静态页面?
这是我的代码:
server = new Server(port);
Resource webRoot = Resource.newResource(webContent);
if (!webRoot.exists()) {
logger.warn("Unable to find root resource:" + webRoot.getName());
} else {
logger.info("Root resource is " + webRoot.getName());
}
ResourceHandler res = new ResourceHandler();
res.setBaseResource(webRoot);
res.setDirAllowed(false);
//servlet handler
ServletContextHandler servletCtx = new ServletContextHandler(ServletContextHandler.SESSIONS);
servletCtx.setContextPath("/service");
servletCtx.addServlet(new ServletHolder("sample", new MyServletSample()), "/sample");
ErrorPageErrorHandler errorHandler = new ErrorPageErrorHandler();
errorHandler.addErrorPage(404, "index.html");
servletCtx.setErrorHandler(errorHandler);
// static file handler
ContextHandler staticCtx = new ContextHandler("/");
staticCtx.setBaseResource(webRoot);
staticCtx.setHandler(res);
// add handlers
HandlerList handlerList = new HandlerList();
handlerList.addHandler(servletCtx);
handlerList.addHandler(staticCtx);
// add handerList to server
server.setHandler(handlerList);
此代码显示localhost:8080上的index.html,我可以访问示例服务http://localhost:8080/service/sample。但是,我想显示一个静态错误页面(即文档),以显示是否出现类似" 404 Not Found"发生。
使用此代码,错误处理程序会记录:
"警告o.e....R.server.handler.ErrorHandler - 未找到错误页面 的index.html"
。定义URI的正确方法/语法是什么?
提前致谢!
答案 0 :(得分:0)
此问题已在https://stackoverflow.com/a/32383973/775715
之前得到解答不要混用ResourceHandler
和ServletContextHandler
,除非你真的知道你在做什么,并完全理解javax.servlet.ServletContext
的性质和所有它带来的规则。
另见:
以下是使用NO ResourceHandler,1 ServletContextHandler和提供静态文件服务的DefaultServlet进行设置的示例。
// servlet handler
ServletContextHandler servletCtx = new ServletContextHandler(ServletContextHandler.SESSIONS);
servletCtx.setContextPath("/");
servletCtx.setBaseResource(webRoot); // what static content to serve
servletCtx.setWelcomeFiles(new String[] { "index.html" });
servletCtx.addServlet(new ServletHolder("sample", new MyServletSample()), "/service/sample");
ErrorPageErrorHandler errorHandler = new ErrorPageErrorHandler();
errorHandler.addErrorPage(404, "/index.html");
servletCtx.setErrorHandler(errorHandler);
// static file serving, and context based error handling
ServletHolder defaultServ = new ServletHolder("default", DefaultServlet.class);
defaultServ.setInitParameter("dirAllowed","false");
servletCtx.addServlet(defaultServ,"/");
// add handlers
HandlerList handlerList = new HandlerList();
handlerList.addHandler(servletCtx);
handlerList.addHandler(new DefaultHandler()); // non-context error handling