Search code examples
jspservletsredirect-loop

This webpage has a redirect loop error


Iam getting error in browser as 'This webpage has a redirect loop' when iam just running my url as 'http://localhost:9090/MyProj/todos/1'

Not understanding how to fix this, please someone look into this and provide me solution.

Below is my code:

web.xml

<?xml version="1.0" encoding="UTF-8"?>

<web-app>

    <servlet>
        <servlet-name>MyServlet</servlet-name>
        <servlet-class>MyServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>MyServlet</servlet-name>
        <url-pattern>/todos/*</url-pattern>
    </servlet-mapping>

</web-app>

MyServlet.java

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class MyServlet
 */
public class MyServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * Default constructor. 
     */
    public MyServlet() {
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.sendRedirect("index.jsp");
    }

}

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
   <%@page import="org.json.JSONObject" %> 


<%

JSONObject obj = new JSONObject();

obj.put("description", "Pick up Milk");
obj.put("status", "incomplete");
obj.put("id", 1);

response.setContentType("application/json");

out.print(obj);
%>

Solution

  • change

    response.sendRedirect("index.jsp");
    

    to

    response.sendRedirect("/MyProj/index.jsp");
    

    without it for example if you hit a GET on /todo1 it will invoke Servlet which will redirect it to /todo1/index.jsp which will get mapped to Servlet again because this is how you mapped it, or you might just want to forward request to jsp