Session-config
We can set the app's session in Web.xml:
<!--1, cookie-config parameters in Session-config and inside are optional, but they must appear sequentially. --> <!--2, these values all have default values, we can not do processing, but based on security considerations, recommended settings. --> <session-config> <!--session-timeout per minute, if <=0, the default for Tomcat is 30 minutes, indicating that if no new request is received within 30 minutes, Think session invalid--> <session-timeout>30</session-timeout> <cookie-config> <name>jsessionid& lt;/name> <!--name, default is Jsessionid--> <!--domain and path corresponding to the domain and path properties in the cookie, these two values are generally default, do not set, Path defaults to the context name of the application--> <domain>flowingflying.com</domain> <path>/aaa</path> <!-- Comment is the comment attribute in the cookie header that is used to parse the user's use of the cookie and to guide the user to the Web site's privacy policy--> <comment>! [Cdata[keeps you logged in. We are private policy for more informcation.] </comment>
In code, you can set up tracking in the Onstartup () of the Servletcontextlistener contextinitialized () and Servletcontainerinitializer Mode and Cookie-config. Set the ServletContext using Setsessiontrackingmodes (), and get Javax.servlet by Getsessioncookieconfig (). Sessioncookieconfig, and then set it.
The following is an example of a configuration:
<session-config>
<session-timeout>30</session-timeout>
<cookie-config>
<path>/chapter05</path>
We notice that some browsers are turned off and then reopened, and the request will still carry the session ID in the cookie, such as Firefox, a lot of desktop browsers, that is, the browser is off, the cookie remains, and it works after reboot. It's up to the browser to decide what to do with it. a small example
This is an example of adding goods to cart cart, not using a database, and using session for storage.
Products are used to store the list of goods ID and product names private final Map<integer, string> product = new hashtable<> (); /* Request with the Product ID, indicating that the user to the ID corresponding to the goods into their own cart/private void AddToCart (HttpServletRequest request, HttpServletResponse
Response) throws ioexception{int productId;
try{productId = Integer.parseint (Request.getparameter ("productId"));
}catch (Exception e) {response.sendredirect ("shop");
Return //getsession () equals getsession (True), gets the session, if none, creates a new and therefore does not return NULL.
If it is getsession (false), gets the session, if none is created, and returns NULL.
HttpSession session = Request.getsession (); In session, the user's cart's key value pair is ("cart", HashMap object), such as none, including no session ID in request requests, and although there is a session ID but does not exist in the Web container (possible web Server reboot, which may expire or something), it is created. The key-value pairs in session are objects that can store complex data structures, not just simple strings.
There is a Session.removeattribute () method for removing key value pairs.
if (Session.getattribute ("cart") = = null) session.setattribute ("Cart", New hashmap<integer,integer> ());
Find the corresponding item ID, if created, number +1. @SuppressWarnings ("unchecked") hashmap<integer,integer> cart = (hashmap<integer,integer>) Session.getattribute ("cart");
if (!cart.containskey (productId)) {cart.put (productId, 0);
} cart.put (Productid,cart.get (productId) + 1);
In the user session of the shopping cart to add goods, call the shopping cart display business, display to the user to see Response.sendredirect ("Shop?action=viewcart");
private void Viewcart (HttpServletRequest request, httpservletresponse response) throws Servletexception, ioexception{
Request.setattribute ("Products", products);
Request.getrequestdispatcher ("/web-inf/jsp/view/viewcart.jsp"). Forward (request, response); }
The above is a Java in the use of the session example, showing the shopping cart, usually in the way of JSP, such as the previous example of the forward to/web-inf/jsp/view/viewcart.jsp in the processing. Use Session.getattribute () to get the information in the session.
<%@ page import= "Java.util.Map"%>
<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >
Other common methods
In addition to the methods used in small examples, HttpSession also has the following common methods: GetId (): Get session ID GetCreationTime (): Create Time Getlastaccessedtime (): User's most recent request with the session ID time IsNew (): is the new session ID Getmaxinactiveinterval (): How long does the request for this session ID arrive, the session is invalid. This time is the <session-timeout> time in the configuration. The corresponding setmaxinactiveinterval can be used to set up for that particular session. For example, the administrator's permissions are higher than the average user, you can set a shorter time for the Administrator's session. Invalidate (): this is usually called when the user logout, which is equivalent to deleting this session. Login and Logout
The following is a successful user login process:
Set an attribute for the session, such as user name
Session.setattribute ("username", username);
Modifying the session ID to prevent users from using a session ID, which is a way to avoid fixation attacks, is supported after Java EE version 7.
Request.changesessionid ();
Redirect to a page after logging in
It is given accordingly:
And in the other servlet:
If not registered, return to the registration interface if
(Request.getsession (). getattribute ("username") = = null) {
response.sendredirect ("/login ");
return;
}
When the user presses logout, for example, the link is/login?logout, then in the login servlet doget add:
if (Request.getparameter ("logout")!= null) {
session.invalidate ();
Response.sendredirect ("login");
return;
}
RELATED links: My professional Java for WEB applications related articles