In this tutorial you will learn how to create session in servlet
Creating A Session Example
To create a new session you need to call the getSession(true) or getSession() methods of the HttpervletRequest interfac.
An example of creating a new session is given below.
login.html
<HTML> <HEAD> <TITLE> Login Page </TITLE> </HEAD> <BODY> <BODY bgcolor=lightblue> <form name=login method="get" action="http://localhost:8080/destroysession/create"> <center> <h1>Enter your Name and Pasword </h1><br> <table border=1> <tr><td>Enter Your Name :</td> <td><input type="text" name="userName" value=""></td> <tr><td align=center><input type="submit" name="Submit" value="Submit" ></td> <td align=center><input type="reset" name="reset" value="Refresh"></td> <table> </center> </form> </BODY> </HTML>
CreateSession.java
package roseindia.net; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; public class CreateSession extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { PrintWriter out = response.getWriter(); response.setContentType("text/html"); String name = request.getParameter("userName"); if (name.equalsIgnoreCase("web")) { out.println("<Center><h3>"); out.println("Creating A New Session..........."); out.println("</h3></Center>"); HttpSession session = request.getSession(true); out.println("<Center><h3>"); out.println("Session Created"); out.println("<br>Session Id - "); out.println(session.getId()); out.println("<br>Session Creation Time - "); out.println(session.getCreationTime()); out.println("<br>Session Last Access Time - "); out.println(session.getLastAccessedTime()); out.println("<br>Session Default MaxInactiveTime - "); out.println(session.getMaxInactiveInterval()); out.println("</h3></Center>"); } else { out.println("<h1>"); out.println("Please enter the name \"web\""); out.println("<h1>"); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { doGet(request, response); } }
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <display-name>CreateSession</display-name> <!-- Servlet --> <servlet> <servlet-name>CreateSession</servlet-name> <servlet-class>roseindia.net.CreateSession</servlet-class> </servlet> <!-- Servlet Mapping--> <servlet-mapping> <servlet-name>CreateSession</servlet-name> <url-pattern>/create</url-pattern> </servlet-mapping> </web-app>When you run this application it will display message as shown below:
[ 0 ] Comments