In the previous article, we learned how to get initialized configuration information, this chapter we learn how to get other built-in objects
Get HttpSession Instance
To get a look at a session object in the Servlet program, you can do so through the HttpServletRequest interface, which provides the following action methods in this interface
1. Public HttpSession getsession ()
2. Public HttpSession getsession (Boolean Create)
The servlet itself provides only requests and response two objects, so if you want to get a session object, you can only rely on the request object because the session belongs to the scope of the HTTP protocol, and every time you send a request, The server will automatically set a cookie for the client, so, naturally, the session to use the mechanism of cookies, but cookies can only be obtained through request, then the natural session can only be obtained through request.
One instance gets the Session object
Package Servletdemo;
Import java.io.IOException;
Import javax.servlet.*;
Import javax.servlet.http.*;
public class HttpSession extends HttpServlet {//inheritance HttpServlet public
void Doget (HttpServletRequest req, HttpServletResponse resp)
throws servletexception,ioexception{ //processing services
Javax.servlet.http.HttpSession Ses=req.getsession ()//Get Session Object
SYSTEM.OUT.PRINTLN ("Session ID:" +ses.getid ())//Get session ID
Ses.setattribute ("username", "Zhao Yuqiang");/Set Properties
System.out.println ("Username property content:" +ses.getattribute ("username") );
}
public void DoPost (HttpServletRequest req,httpservletresponse resp)
throws servletexception,ioexception{// Process POST Request
This.doget (req, resp); Call Doget () method
}
}
Configure the Web.xml file after
<servlet>
<servlet-name>session</servlet-name>
<servlet-class> servletdemo.httpsession</servlet-class>
</servlet>
<servlet-mapping>
< servlet-name>session</servlet-name>
<url-pattern>/HttpSessionTest</url-pattern>
</servlet-mapping>
You can now get the session object.