Wednesday, 3 September 2014

Simple Example on Session

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
    <servlet>
        <servlet-name>DisplaySession</servlet-name>
        <servlet-class>DisplaySession</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>DisplaySession</servlet-name>
        <url-pattern>/DisplaySession</url-pattern>
    </servlet-mapping>
</web-app>

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.*;

public class DisplaySession extends HttpServlet {
    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse res)throws ServletException, IOException{
        try(PrintWriter out = res.getWriter()){
            StringBuilder msg = new StringBuilder();
            HttpSession mySession = req.getSession();
            Integer accessCount = (Integer)mySession.getAttribute("count");
            if(accessCount == null){
               msg.append("Welcome");
               mySession.setAttribute("count", 0);
               accessCount = 0;
            }
            else{
                accessCount = accessCount + 1;
                mySession.setAttribute("count", accessCount);
                msg.append("Welcome Back");
            }
            
            String sessionId = mySession.getId();
            long createdTime = mySession.getCreationTime();
            long lastAccessedTime = mySession.getLastAccessedTime();
            
            out.println("<html><head><title>Your Session Data</title></head>");
            out.println("<body><h1>" + msg);
            out.println("Your visit count " + accessCount +"<br />");
            out.println("Session Id :" + sessionId +"<br />");
            out.println("Created Time :" + createdTime +"<br />");
            out.println("Last Accessed Time :" + lastAccessedTime +"<br />");
            out.println("</h1></body></html>");
        }
    }   
}


Sample Output
 Refresh the page, then you can able to see the output like below.





Prevoius                                                 Next                                                 Home

No comments:

Post a Comment