The Java Web session technology

Source: Internet
Author: User

Some data is generated during client-to-server communication. For example, A and B respectively landed a treasure shopping site, a bought an Android phone, B bought an iphone, when the checkout, the Web server needs to separate the user A and B information separately. According to the Java Web servlet technology, both the HttpServletRequest object and the ServletContext object can hold the data, but these are not suitable for use in this case.

    • Each time the client requests, the server produces a HttpServletRequest object that only holds the data that is passed by this request. Because purchase and checkout are two different requests, saving information using the HttpServletRequest object can be lost.
    • The same web App shares a ServletContext object, so it's obviously not possible to distinguish which product was purchased by multiple users when they checkout.
1. Cookie Object

A cookie is a session technology that is used to keep the data in a session in the user's browser, allowing better interaction between the browser and the server. When the server sends a cookie to the client, it increments the Set-cookie field in the HTTP Response header field, which sets a cookie that follows certain rules, such as saving as a key-value pair, which can have more than one property value, but must be separated by semicolons and spaces. The following is an example of a cookie:

Set-cookie: "Lasttime=" 2016-05-21 12:03:10 "; Version=1 "
Cookie usage

In order to encapsulate cookie information, a Javax.servlet.http.Cookie class is provided in the Servlet API that contains methods for generating cookie information and extracting various attributes of cookie information, with the cookie being the only constructed method:

Public Cookie (java.lang.String name, java.lang.String value)

In the constructor method, name is used to specify the cookie name, value specifies the cookie, and note that once the cookie is created, its name is not allowed to change, and the cookie value can be changed. Cookie classes are commonly used in the following ways:

Method Function
String GetName () return cookie Name
void SetValue (String newvalue)/string GetValue () Set/Get Cookie value
void setmaxage (int expiry)/int getmaxage () Sets/Gets the number of seconds that a cookie is saved in the browser
void SetPath (String uri)/public string GetPath () Set/Get cookie to valid directory path
void SetDomain (String pattern)/string GetDomain () Set/Get a valid domain for cookies
void SetSecure (Boolean flag)/boolean getsecure () Sets/Gets whether the cookie can only be transmitted using secure protocol

Cookie Example

Use cookie technology to prompt for the last access time feature.

Package Zzz;import Java.io.ioexception;import Java.io.printwriter;import java.text.simpledateformat;import Java.util.date;import Javax.servlet.annotation.webservlet;import Javax.servlet.http.cookie;import Javax.servlet.http.httpservlet;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.HttpServletResponse; @WebServlet (name= "CookieTest", urlpatterns={"/CookieTest"}) public class CookieTest extends HttpServlet {@Override public void doget (HttpServletRequest request, HttpServletResponse respons        E) throws IOException {//Specify the response encoding method Response.setcontenttype ("Text/html;charset=utf-8");                PrintWriter out = Response.getwriter ();        String lasttime = null;        cookie[] cookies = request.getcookies (); for (int i = 0; cookies = null && i < cookies.length; i++) {if (Cookies[i].getname () Equals ("Lastt            IME ") {lasttime = Cookies[i].getvalue (); }} if (Lasttime = = nulL) {out.println ("Hello, this is your first visit to the website");        } else {out.println ("Hello, last time you visited the website is:" + lasttime); }//Create a cookie, record the current time into a cookie and return a String of times = new SimpleDateFormat ("Yyyy-mm-dd hh:mm:ss"). Format (NE        W Date ());        Cookie cookie = new Cookie ("Lasttime", time);    Response.addcookie (cookie);        } @Override public void DoPost (HttpServletRequest request, httpservletresponse response) throws IOException {    This.doget (request, response); }}

2. Session Technology

Cookie technology can save user information in the browser, and can share data in multiple requests, but if the message is more, the use of cookie technology significantly increase the processing difficulty of the service-side program. At this point, you can use session technology to do this by keeping the sessions data on the server side. Note: The session object corresponds to an ID, so it is generally necessary for the client to record the ID of the object, usually the session is passed the Session object ID through the cookie technology.

The session object is closely related to each request, and HttpServletRequest defines the GetSession () method used to get the session object, as follows:

Public HttpSession getsession (Boolean create);p ublic HttpSession getsession ();

The first getsession () determines whether a new session object is created based on the value of the parameter, and if the argument is true, the associated HttpSession object does not exist when a new HttpSession object is created, and if the argument is false, A new HttpSession object is not created. The second getsession () method is equivalent to the case where the first method parameter is true. HttpSession common methods are as follows:

Method Function
String GetId () Returns the session identification number associated with the HttpSession object
int Getmaxinactiveinterval () Returns the maximum lifetime of the current HttpSession object, in S
void Invalidate () Force the HttpSession object to expire
void SetAttribute (String name, Object value) To associate an object with a name and store it in a HttpSession object
Object getattribute (String name) Returns the Property object for the specified name in the current HttpSession object
void RemoveAttribute (String name) Removes the specified Name Property object from the current HttpSession object

When the Web server manages the HttpSession object, it uses a time-out management mechanism to determine whether the customer's order is still being accessed. For a certain period of time, a customer has not been accessed, and the Web server will assume that the client has ended the request, and that the HttpSession object associated with the client session will be garbage collected. If the client then accesses it again, a new HttpSession object is recreated. The effective time of the session can be set in Web. XML, the default value is the servlet container definition, in the Tomcat installation directory of Web. XML in the following configuration, is to set the session time-out, in minutes.

<session-config>    <session-timeout>30</session-timeout></session-config>
session Example

The session technology is used to prompt the last access time function.

Package Zzz;import Java.io.ioexception;import Java.io.printwriter;import java.text.simpledateformat;import Java.util.date;import Javax.servlet.annotation.webservlet;import Javax.servlet.http.cookie;import Javax.servlet.http.httpservlet;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;import javax.servlet.http.HttpSession; @WebServlet (name= "Sessiontest", urlpatterns={"/sessiontest"}) public class Sessiontest extends HttpServlet {@Override public void doget (HTTPSERVLETR Equest request, HttpServletResponse response) throws IOException {//Specify Response encoding Response.setcontenttype ("text        /html;charset=utf-8 ");                PrintWriter out = Response.getwriter ();        String user = null;        cookie[] cookies = request.getcookies (); for (int i = 0; cookies = null && i < cookies.length; i++) {if (Cookies[i].getname (). Equals ("User"            ) {user = Cookies[i].getvalue ();      }        }          HttpSession session = Request.getsession ();            if (user = = null) {out.println ("Hello, this is your first visit to the website");            Cookie cookie = new Cookie ("User", "luoxn28");        Response.addcookie (cookie);            } else {String time = (string) session.getattribute ("Lasttime");        Out.println ("Hello, the last time you visited the site is:" + times);        } String lasttime = new SimpleDateFormat ("Yyyy-mm-dd hh:mm:ss"). Format (new Date ());    Session.setattribute ("Lasttime", lasttime);        } @Override public void DoPost (HttpServletRequest request, httpservletresponse response) throws IOException {    This.doget (request, response); }}

The Java Web session technology

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.