February 27, 2011

Servlets - Session Management Example

After user authentication, start a session. Display "Welcome [username]" as the response along with a link that hits another Servlet. From this other servlet, send the response "You are [username]" by retrieving the username information from the session as an attribute.


1) Servlet 1: Code here - http://www.javaissues.com/2011/02/servlets-handling-get-request.html


2) Servlet 2 - PostServlet.java

package info.icontraining.servlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.*;

public class PostServlet extends HttpServlet {
 
   public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
      PrintWriter out = response.getWriter();
       
      String username = request.getParameter("user");
      String passwd = request.getParameter("pass");
      out.println("<html>");
      out.println("<head><title>Post Servlet Example</title></head>"); 
      out.println("<body><h1>");
       
      if (username.equals("dinesh") && passwd.equals("dinesh")) {

         out.println("Welcome " + username +"!<br/><br/>");
         HttpSession session = request.getSession();
         session.setAttribute("username",username);
         out.println("<a href=\"linkedServlet\">Click here</a>");

      } else {
         out.println("Invalid username/passwd. Go back and try again.");
      }
       
      out.println("</h1></body></html>");
      out.close();
   }
}


3) Servlet 3 - LinkedServlet.java

package info.icontraining.servlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.*;

public class LinkedServlet extends HttpServlet {
 
   public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
      PrintWriter out = response.getWriter();
       
      out.println("<html>");
      out.println("<head><title>Session Management Example</title></head>"); 
      out.println("<body><h1>");
             
      HttpSession session = request.getSession();
      String username = (String)session.getAttribute("username");
      out.println("You are " + username +"!");
       
      out.println("</h1></body></html>");
      out.close();
   }
}


web.xml configuration for Servlets 2 & 3 (for configuration of Servlet 1, go to link specified above)

<servlet>
    <servlet-name>postServlet</servlet-name>
    <servlet-class>info.icontraining.servlets.PostServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>postServlet</servlet-name>
    <url-pattern>/formurl</url-pattern>
</servlet-mapping>
 
<servlet>
    <servlet-name>linkedServlet</servlet-name>
    <servlet-class>info.icontraining.servlets.LinkedServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>linkedServlet</servlet-name>
    <url-pattern>/linkedServlet</url-pattern>
</servlet-mapping>

1 comment: