简体   繁体   English

dispatcher.forward导致无限循环

[英]dispatcher.forward causes infinite loop

I am trying to do the following: I create a servlet to handle all requests, and if the url contains the word "hello", then set the response code to 403, otherwise forward the request to an html page. 我正在尝试执行以下操作:创建一个servlet处理所有请求,如果url包含单词“ hello”,则将响应代码设置为403,否则将请求转发到html页面。 Here is my servlet: 这是我的servlet:

@WebServlet("/*")
public class AllRequestsHandlerServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String url = request.getRequestURL().toString();
        if(url.contains("hello")) {
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        } else {
            RequestDispatcher dispatcher = request.getRequestDispatcher("/static-html-page.html");
            dispatcher.forward(request, response);
        }
    }
}

But after forwarding, since this servlet handles the forwarded request too, it causes an infinite loop. 但是在转发之后,由于此servlet也处理转发的请求,因此会导致无限循环。 How can I avoid that? 我该如何避免呢?

This will never work because /* maps to every request - including your forward to /static-html-page.html and path mappings take priority over all other mappings. 这永远不会起作用,因为/*映射到每个请求-包括转发到/static-html-page.html路径,路径映射的优先级高于所有其他映射。

There are a couple of ways around this. 有两种解决方法。 The simplest (assuming no other content in the web app) would be: 最简单的方法(假设Web应用程序中没有其他内容)是:

  • rename /static-html-page.html to /static-html-page.jsp /static-html-page.html重命名为/static-html-page.jsp
  • change the mapping from /* to / 将映射从/*更改为/

That does mean that /static-html-page.jsp would be directly accessible. 这确实意味着/static-html-page.jsp可以直接访问。 If you don't want that, move it under /WEB-INF . 如果您不想这样做,请将其移至/WEB-INF request.getRequestDispatcher("/WEB-INF/static-html-page.html") will still work. request.getRequestDispatcher("/WEB-INF/static-html-page.html")仍然可以使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM