如何修复 servlet 中的重定向循环 url-pattern like "users/*"

How to fix redirect looping in servlet url-pattern like "users/*"

我在为 servlet 设置 url-pattern 时遇到问题。如果我将它设置为 "users/*" 之类的东西,在 forwart() 或 include() 到 jsp 之后,我会得到一个重定向循环。

这是我的代码:

@WebServlet("/users/*")
public class UserServlet extends HttpServlet {
    protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

        String[] pathParts = request.getPathInfo().split("/");

        int id = Integer.valueOf(pathParts[1]);

        request.setAttribute("userId", id);
        request.getRequestDispatcher("user.jsp").include(request, response);
    }
}

尝试按如下方式更改您的 servlet:

@WebServlet("/users")
public class UserServlet extends HttpServlet {
    protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

        String[] pathParts = request.getPathInfo().split("/");

        int id = Integer.valueOf(pathParts[1]);

        request.setAttribute("userId", id);
       getServletContext().getRequestDispatcher("/user.jsp").forward(request, response);
    }

}

只需将“/”添加到您的 jsp 页面

 getServletContext().getRequestDispatcher("/user.jsp").forward(request, response);

所以这里有什么不同???

如果您直接指定 user.jsp 服务器检查 user.jsp 例如如果 Tomcat 被用作网络服务器那么服务器检查user.jsp 在 /webapp 文件夹中(所有应用程序所在的位置。)。

所以 user.jsp 在哪里???它在您的应用程序中,例如 "JSPTurorial"。如果你想在你的应用程序中引用 user.jsp 你应该给出相对路径 "/user.jsp" 这样你的服务器就会检查这里 "http://localhost:8080/JSPTutorial/user.jsp" as server is executing the files in /JSPTutorial directory else it will check here "http://localhost:8080/user.jsp"该路径将不可用。