Servlet Chaining using SendRedirect


        Sends a redirect response to the client using the specified redirect location URL. The url passed to this method should be relative.

        SendRedirect method should be executed only once pre response object, If you try to call this method twice using same response it will throw the message "response has already been committed"
	response.sendRedirect("relative_url");

Key points
            1. We cannot send post request using redirect
            2. While redirecting a page request and response object from the current page will killed
            3. New request and response will be created for newly loaded or redirected page page
            4. We can use both relative and absolute url with sendRedirect 
                    Example: response.sendRedirect("ui/index.htnl") or response.sendRedirect("http://....../ui/index.htnl")

Example:
Servlet code
package com.candidjava;

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 TestController
 */
public class TestController extends HttpServlet {
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String un=request.getParameter("username");
		String pw=request.getParameter("password");
		System.out.println("data received");
		System.out.println(un +"  "+ pw);
	
		response.sendRedirect("newpage.html");
		
	}

}

ScreenShot
                        
            

Download:
Sendredirect example war
Sendredirect example zip

Looking for RequestDispatcher tutorial




Related Post

Comments


©candidjava.com