Search code examples
javajspservletsurl-patternredirect-loop

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


I have a problem with setting url-pattern for servlet. If I set it to something like "users/*", after forwart() or include() to jsp, I get a redirect looping.

Here is my code:

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

Solution

  • Just add "/" to your jsp page

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

    So what made difference here ???

    If you directly specify user.jsp Server check user.jsp in default directory for example if Tomcat is used as webserver then server checks for user.jsp in /webapp folder (Where all applications resides.).

    so where is user.jsp located ??? Its in your application for example "JSPTurorial". If you want reference user.jsp in your application you should give the relative path "/user.jsp" so that your server will check here "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" which will not be available at that path.