@WebServlet("/")
public class RootServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String pathInfo = request.getServletPath();
switch(pathInfo) {
case "/":
this.handleHomePage(request, response);
break;
default:
request.getRequestDispatcher(pathInfo).forward(request, response);
}
}
我正在尝试使用默认的servlet来捕获上下文根URL。因此,当它是根URL时,它将由handleHomePage方法处理。如果没有,它将被转发到相应的文件。例如css,html,图像文件。但这会导致永无止境的异常发生。 getRequestDispatcher是否允许转发到静态页面?
答案 0 :(得分:0)
您最好创建一个这样的过滤器:
@WebFilter(filterName = "rootFilter", urlPatterns = { "/*" }, dispatcherTypes = { DispatcherType.REQUEST })
{
@Override
public void doFilter(ServletRequest p_oRequest, ServletResponse p_oResponse, FilterChain p_oChain) throws IOException, ServletException
{
// skip non-http requests
if(!(p_oRequest instanceof HttpServletRequest))
{
p_oChain.doFilter(p_oRequest,p_oResponse);
}
else
{
String pathInfo = ((HttpServletRequest)p_oRequest).getServletPath();
switch(pathInfo)
{
case "/":
// Forward to your "root servlet"
break;
default:
p_oChain.doFilter(p_oRequest,p_oResponse);
}
}
}
}
注意:此代码未经测试,未检查语法错误。