How To Redirect from JSP to Servlet?

In this short post, I will show you how to redirect from JSP to Servlet?.
We can make use of the method:
    response.sendRedirect( <thePageUrl> )
Here's a quick example. The file test-redirect.jsp will send a redirect to the HelloWorldServlet. The HelloWorldServlet has a URL mapping of "/hello".

File: test-redirect.jsp

Here's the code for the JSP
<%
    response.sendRedirect(request.getContextPath() + "/hello");
%>

File: HelloWorldServlet.java

Here's the code for the Servlet. Make note of the URL mapping "/hello".
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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

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

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        
        out.println("Hello world: " + new java.util.Date());
    }

}
When you run the JSP file, test-redirect.jsp. It will automatically redirect to the servlet.
That's it! Enjoy :-)

Comments