Sandeep Shah
Sandeep Shah

Reputation: 169

How do you fix infinite redirects to a Servlet?

I have a Servlet mapped as follows:

@WebServlet("/test/*")

So that everything accessing localhost:8080/test/1 or localhost:8080/test/99 is handled in the same Servlet and forward them to localhost:8080/test/1/test.html

The problem is that - my forwarding is falling under the same wildcard rule which is test/* - and is causing an infinite loop.

I've tried to fix this with no luck. I've been thinking of adding some kind of counter to keep track of how many times the Servlet has been called, but that would only limit me and create another problem if I want to reuse the Servlet properly.

All help is appreciated since I've been stuck with this the whole day. Thank you thank you thank you!

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

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            System.out.println(request.getRequestURL());
            RequestDispatcher view = request.getRequestDispatcher("test.html");
            view.forward(request, response);    
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}

Resolution: I used the WEB-INF directory to store your html views. You can forward there without hitting any servlet mappings. I thought this would solve it but it still gives me the same problem.

 RequestDispatcher view = request.getRequestDispatcher("WEB-INF/views/login.html");

Output when requesting http://localhost:8080/test/test:

2016-05-15T21:12:37.798+0200|Info: http://localhost:8080/test/test
2016-05-15T21:12:37.798+0200|Info: http://localhost:8080/test/WEB-INF/views/login.html
2016-05-15T21:12:37.798+0200|Info: http://localhost:8080/test/WEB-INF/views/WEB-INF/views/login.html
2016-05-15T21:12:37.798+0200|Info: http://localhost:8080/test/WEB-INF/views/WEB-INF/views/WEB-INF/views/login.html
2016-05-15T21:12:37.798+0200|Info: http://localhost:8080/test/WEB-INF/views/WEB-INF/views/WEB-INF/views/WEB-INF/views/login.html

Upvotes: 1

Views: 295

Answers (1)

Kayaman
Kayaman

Reputation: 73528

Use the WEB-INF directory to store your html views. You can forward there without hitting any servlet mappings.

Upvotes: 1

Related Questions