How to send redirect from Java Servlet

Hello friends, Today I am going to show you how to send redirect from Java Servlet. In this example, we will use how to send redirects from Java Servlet.

At a glance of SendRedirect

  • This is the HttpServlerResponse object’s method.
  • The client (Browser) receives the request and processes the new URL.
  • The end-user may see where the URL is being redirected.
  • In Nutshell, Processing is done on the client-side.

We can use SendRedirect in the doGet() and doPost() method. As a result, a new URL will be exposed in the URL tab.

Example of SendRedirect:

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		if (request.getParameter("delete_id") != null) {
			---------------------------
			response.sendRedirect(request.getContextPath() + "/coursetable.jsp");
		} 
	}

In doPost() method:

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

		if (request.getParameter("register") != null) {
---------------------------
---------------------------
			response.sendRedirect(request.getContextPath() + "/coursetable.jsp");
		} else if (request.getParameter("update") != null) {
			-------------------
-----------------
			response.sendRedirect(request.getContextPath() + "/coursetable.jsp");
		}

	}

Hope it helps!

Leave a Reply