Subscribe For Free Updates!

We'll not spam mate! We promise.

Thursday, May 23, 2013

Servlets Forward and sendRedirect

When we want that someone else should handle the response of our servlet, then there we should use sendRedirect() method.In send Redirect whenever the client makes any request it goes to the container, there the container decides whether the concerned servlet can handle the request or not.   If not then the servlet decides that the request can be handle by other servlet or jsp. Then the servlet calls the sendRedirect() method of the response object and sends back the response to the browser along with the status code. Then the browser sees the status code and look for that servlet which can now handle the request.   Again the browser makes a new request, but with the name of that servlet which can now handle the request and the result will be displayed to you by the browser. In all this process the client is unaware of the processing. 
 
Page redirection is generally used when a document moves to a new location and we need to send the client to this new location or may be because of load balancing, or for simple randomization.
The simplest way of redirecting a request to another page is using method sendRedirect() of response object. Following is the signature of this method:

public void HttpServletResponse.sendRedirect(String location)
throws IOException 
This method sends back the response to the browser along with the status code and new page location. You can also use setStatus() and setHeader() methods together to achieve the same:
....
String site = "http://www.newpage.com" ;
response.setStatus(response.SC_MOVED_TEMPORARILY);
response.setHeader("Location", site); 
....

Example

SendRedirect.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Redirecting the page</title>
</head>
<body>
 <form action = "/ServletProject/SendRedirect" method = "post">
 <tr>
  <td>Enter your name :</td>
  <td><input type = "text" name = "username"></td>
 </tr><br>
 <tr>
  <td>Enter your password :</td>
  <td><input type = "password" name = "password"></td>
 </tr><br>
 <tr>
  <td><input type = "submit" name = "submit"></td>
 </tr>
 </form>
</body>
</html>
 
 
 
web.xml
 
 
<servlet>
     <servlet-name>SendRedirect </servlet-name>
     <servlet-class>SendRedirect </servlet-class>
 </servlet>

 <servlet-mapping>
     <servlet-name>SendRedirect </servlet-name>
     <url-pattern>/SendRedirect </url-pattern>
 </servlet-mapping>
.... 
 
SendRedirect.java
 
import java.io.*;

        import java.io.IOException;

        import javax.servlet.ServletException;

        import javax.servlet.http.HttpServletRequest;

        import javax.servlet.http.HttpServletResponse;

        

 public class SendRedirect extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {

 public SendRedirect() {

  super();

 } 

 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws 

        ServletException, IOException {

  // TODO Auto-generated method stub

  response.setContentType("text/html");

  PrintWriter pw = response.getWriter();

  String name = request.getParameter("username");

  String password = request.getParameter("password");

  if(name.equals("James")&& password.equals("abc"))

  {

   response.sendRedirect("/ServletProject/ValidUser");

  }

  else

  {

   pw.println("u r not a valid user");

  }

 } 

        } 
 
ValidUser.java
 
 mport java.io.*;

        import java.io.IOException;

        import javax.servlet.ServletException;

        import javax.servlet.http.HttpServletRequest;

        import javax.servlet.http.HttpServletResponse;

        

        /**

 * Servlet implementation class for Servlet: ValidUser

 *

 */

 public class ValidUser extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {

    /* (non-Java-doc)

  * @see javax.servlet.http.HttpServlet#HttpServlet()

  */

 public ValidUser() {

  super();

 } 

        

 /* (non-Java-doc)

  * @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)

  */

 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws 

        ServletException, IOException {

  // TODO Auto-generated method stub

        

 } 

        

 /* (non-Java-doc)

  * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)

  */

 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws 

        ServletException, IOException {

  // TODO Auto-generated method stub

  PrintWriter pw = response.getWriter();

  pw.println("Welcome to roseindia.net<br>");

  pw.println("how are you");

 } 

        } 
 
The code of the program is given below:





 
 
Forward Vrs sendRedirect 
A Controller (in this context, an implementation of HttpServlet) may perform either a forward or a redirect
operation at the end of processing a request. It's important to understand the 
difference between these two cases, in particular with respect to browser reloads 
of web pages.

Forward
  • a forward is performed internally by the servlet
  • the browser is completely unaware that it has taken place, so its original URL remains intact
  • any browser reload of the resulting page will simple repeat the original request, with the original URL
Redirect
  • a redirect is a two step process, where the web application instructs the browser to fetch a second URL, which differs from the original
  • a browser reload of the second URL will not repeat the original request, but will rather fetch the second URL
  • redirect is marginally slower than a forward, since it requires two browser requests, not one
  • objects placed in the original request scope are not available to the second request
In general, a forward should be used if the operation can be safely repeated upon a browser reload of the resulting web page; otherwise, redirect must be used. Typically, if the operation performs an edit on the datastore, then a redirect, not a forward, is required. This is simply to avoid the possibility of inadvertently duplicating an edit to the database. More explicitly (in terms of common SQL operations) :
  • for SELECT operations, use a forward
  • for INSERT, UPDATE, or DELETE operations, use a redirect
In HTML, a <FORM> tag can either GET or POST its data. In this context, a GET corresponds to a SELECT-then-forward, and a POST corresponds to an edit-then-redirect. It is strongly recommended that forms for the input of search criteria should use GET, while forms for editing database records should use POST.
Example
This example is after the style of the WEB4J Controller class. The important methods of the Servlet API are :


String nextJSP = "/searchResults.jsp";
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(nextJSP);
dispatcher.forward(request,response);


Socializer Widget
SOCIALIZE IT →
FOLLOW US →
SHARE IT →

0 comments:

Post a Comment