0
@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 是否允许转发到静态页面?

4

1 回答 1

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);
            }
        }
    }
}

注意:此代码未经测试,未检查语法错误。

于 2013-05-13T06:33:31.323 回答