Monday, September 20, 2010

Passing Objects between Servlets

In this example we will see how to create class files, create objects with user input values and pass object from one servlet to another.

Step 1 : Create Java Class File.
Objects are an instance of a Class. So, we need a class file as a structure to create objects from user input values.

Create a java class file named "User.java".

public class User {
   private String name;
   private String email;

   public User(String n, String e) {
     this.name = n;
     this.email = e;
   }

   public String getName() {
     return name;
   }

   public String getEmail() {
     return email;
   }
}



Step 2 : Create HTML or JSP page to accept user input.

Enter the following code in the body tag of your code

<form action="servlet1">
  Name : <input type="text" name="username"/>
<br/>
  Email ID : <input type="text" name="emailid"/>
<br/>
<input type="submit" value="OK"/>
</form>


Step 3 : Create First Servlet to create object and store the user input values.(in my case named "servlet1").

Enter the following code in the doGet() of the servlet.


//assuming request as the object of the HttpServletRequest Class.
//assuming response as the object of the HttpServletResponse Class.

//creating an object named "newUser" of the class User & passing user input values as parameter to the constructor.

User newUser = new User(request.getParameter("username"),request.getParameter("emailid"));

//set a string value (eg."userData") for the object "newUser" to be able to access it from another servlet.

request.setAttribute("userData", newUser);

//passing the control to the second servlet named "servlet2"  using RequestDispatcher.

RequestDispatcher rd = request.getRequestDispatcher("servlet2");
rd.forward(
request, response);

Step 4 : Create Second Servlet to retrive object data and display it to the user.

Enter the following code in the doGet() of the servlet.


//assuming request as the object of the HttpServletRequest Class.
//assuming response as the object of the HttpServletResponse Class.

//get the "userData" attribute from servlet1 and store it in variable "u" of the type "User" created earlier.
//also do not forget to typecast the attribute to the desired type.

User u = (User) request.getAttribute("userData");

//finally print the values using the getter methods of the User Class.

response.getWriter().println("Name : " + u.getName());
response.getWriter().println("Email : " + u.getEmail());



Finally, run the HTML or JSP page. 

No comments:

Post a Comment