In such a case, the container creates a consultation identityentification for every user.The container makes use of this identityentification to become aware of the precise user. An item of HttpSession may be used to carry out tasks:
There are two methods provided by the HttpServletRequest interface to get the object of httpSession:
In this example, we're putting the characteristic withinside the consultation scope in a single servlet and getting that cost from the consultation scope in some other servlet. To set the characteristic withinside the consultation scope, we've got used the setAttribute() technique of HttpSession interface and to get the characteristic, we've got used the getAttribute technique.
Index.html
<form action="servlet1"> Name:<input type="text" name="userName"/><br/> <input type="submit" value="go"/> </form>
FirstServlet.java
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class FirstServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response){ try{ response.setContentType("text/html"); PrintWriter out = response.getWriter(); String n=request.getParameter("userName"); out.print("Welcome "+n); HttpSession session=request.getSession(); session.setAttribute("uname",n); out.print("<a href='servlet2'>visit</a>"); out.close(); }catch(Exception e){System.out.println(e);} } }
SecondServlet.java
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class SecondServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) try{ response.setContentType("text/html"); PrintWriter out = response.getWriter(); HttpSession session=request.getSession(false); String n=(String)session.getAttribute("uname"); out.print("Hello "+n); out.close(); }catch(Exception e){System.out.println(e);} } }
Web.xml
<web-app> <servlet> <servlet-name>s1</servlet-name> <servlet-class>FirstServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>s1</servlet-name> <url-pattern>/servlet1</url-pattern> </servlet-mapping> <servlet> <servlet-name>s2</servlet-name> <servlet-class>SecondServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>s2</servlet-name> <url-pattern>/servlet2</url-pattern> </servlet-mapping> </web-app>
download this example (developed using Myeclipse IDE)