我在为我的Web应用程序设置处理程序时遇到了问题,我想要的是:让HTTPServlet
通过doGet
和doPost
方法处理一些请求(如何从这些方法中加载JSP页面?),也能够加载静态内容(html,JS,CSS)。
我现在设置的方式,我只能有一个或另一个,我不能让两个都工作。
我将解释:
Server server = new Server(5000);
// This is the resource handler for JS & CSS
ResourceHandler resourceHandler = new ResourceHandler();
resourceHandler.setResourceBase(".");
resourceHandler.setDirectoriesListed(false);
// This is the context handler for the HTTPServlet
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/");
context.addServlet(new ServletHolder(new Main()),"/*");
// this is the Handler list for both handlers
HandlerList handlerList = new HandlerList();
handlerList.setHandlers(new Handler[] { context ,resourceHandler});
/*
If I add them in this order,
all requests will be handled by the "context" and no static resource is loaded
If I invert the order, the index page page is loaded by the resource handler, which means,
If I activate directory listings, it gives me a list of all directories, otherwise it's just a blank page
I tried working with a WebAppContext to load JSP pages
but I still had some problems with which handler should handle which requests
*/
server.setHandler(handlerList);
server.start();
server.join();
我遇到的问题是,我的HTTP servlet的行为方式如下:处理所有请求,不给资源处理程序留下任何内容,因此当脚本请求.js
脚本时,它返回一个空的HTML页面。下面是一个示例:
WebAppContext root = new WebAppContext();
root.setParentLoaderPriority(true);
root.setContextPath("/");
root.setResourceBase(".");
root.setWelcomeFiles(new String[] {"test.jsp"});
root.addServlet(new ServletHolder(new Main()),"/*");
HandlerList handlerList = new HandlerList();
handlerList.setHandlers(new Handler[] { root });
在本例中,当使用根处理程序而不使用Main
servlet时,它加载所有静态内容和jsp页面,但当添加主servlet时,它不再加载任何静态内容,并以空的HTML页面响应所有静态内容请求。
1条答案
按热度按时间yyyllmsg1#
当您使用servlet时,servlet链的末端总是有一个终止。
这将是:
DefaultServlet
(使用完整的WebAppContext
时)Default404Servlet
(当使用更简单的设置时,如ServletContextHandler
)如果您只想让
ResourceHandler
提供静态内容,那么就使用DefaultServlet
(它是一个更好的选择,也支持更多的功能)。例如范围请求、高速缓存、自动gzip、内存Map文件服务等)范例: