February 27, 2011

Servlets - Session Management with URL Rewriting

Enable session management through URL rewriting by encoding all the response URLs for the exercise posted at this link - http://www.javaissues.com/2011/02/servlets-session-management-example.html

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

2) Servlet 2

package info.icontraining.servlets;

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

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

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=\"" + response.encodeURL("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 - Code here (of Servlet 3): http://www.javaissues.com/2011/02/servlets-session-management-example.html


web.xml configuration for all 3 servlets same as for the example at this link - http://www.javaissues.com/2011/02/servlets-session-management-example.html


To test Session Management with URL rewriting disable cookies in your browser and access the servlets starting with Servlet 1. Observe URL in browser address bar for re-written URL

No comments:

Post a Comment