Java web session simple application, Java web session

Source: Internet
Author: User
Tags set cookie

Java web session simple application, Java web session

Java sessions are divided into Cookie and HttpSession.
Cookie technology: session data is stored on the browser client.
Session technology: Session data is stored on the server.
I. The following describes the Cookie application.
1. Cookie technology core
Cookie: used to store session data

1) construct a Cookie object
Cookie (java. lang. String name, java. lang. String value)
2) Set cookie
Void setPath (java. lang. String uri): sets a valid cookie access path.
Void setMaxAge (int expiry): sets the cookie validity period.
Void setValue (java. lang. String newValue): sets the cookie value.
3) Send the cookie to the browser to save it.
Void response. addCookie (Cookie cookie): Send cookie
4) The server receives cookies.
Cookie [] request. getCookies (): receive cookies

2. Cookie principles
1) The server creates a cookie object and stores session data in the cookie object.
New Cookie ("name", "value ");
2) the server sends cookie information to the browser
Response. addCookie (cookie );

Example: set-cookie: name = eric (hides the response header that sends a set-cookie name)
3) the browser obtains the cookie sent by the server and saves it on the browser side.
4) when the browser accesses the server next time, it will carry the cookie information
For example, cookie: name = eric (hiding a request header with a name called cookie)
5) The server receives the cookie information from the browser.
Request. getCookies ();

3 Cookie details
1) void setPath (java. lang. String uri): sets a valid cookie access path. The valid path indicates where the valid path of the cookie is stored. the browser will carry the cookie information when accessing the server in the valid path. Otherwise, the cookie information is not included.

2) void setMaxAge (int expiry): sets the cookie validity period.
Positive Integer: indicates the cache directory (in hard disk) of the browser for storing cookie data, and the value indicates the time when the data is saved.
Negative integer: indicates that the cookie data is stored in the memory of the browser. When the browser closes the cookie, it will be lost !!
Zero: the cookie data with the same name is deleted.
3) The Cookie data type can only be non-Chinese string type. Multiple cookies can be saved, but browsers generally only allow 300 cookies to be stored. Each site can store up to 20 cookies. The size of each cookie is limited to 4 kb.
4. The following is the Cookie application code.

1) set Cookie

1 package com. vastsum; 2 3 import java. io. IOException; 4 import javax. servlet. servletException; 5 import javax. servlet. annotation. webServlet; 6 import javax. servlet. http. cookie; 7 import javax. servlet. http. httpServlet; 8 import javax. servlet. http. httpServletRequest; 9 import javax. servlet. http. httpServletResponse; 10 11/** 12 * Servlet implementation class CookieDemo13 */14 @ WebServlet ("/CookieDemo") 15 public class CookieDemo extends HttpServlet {16 17 protected void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {18 // create Cookie Object 19 Cookie cookie = new Cookie ("name", "shutu008"); 20/** 21 * if no path is set, indicates 22 * in the root directory of the current project. If the setting path is saved in the specified directory 23 */24 // setting is saved in the/test directory, set the Cookie object path, if this parameter is set, the Cookie is not in the root directory. 25 cookie. setPath ("/test"); 26 // sets the cookie time. The default time granularity is second 27 cookie. setMaxAge (1000); 28 // send the Cookie object to the browser 29 response. addCookie; 30 31} 32 33 34}

2) get cookie

1 package com. vastsum; 2 3 import java. io. IOException; 4 import javax. servlet. servletException; 5 import javax. servlet. annotation. webServlet; 6 import javax. servlet. http. cookie; 7 import javax. servlet. http. httpServlet; 8 import javax. servlet. http. httpServletRequest; 9 import javax. servlet. http. httpServletResponse; 10 11/** 12 * Servlet implementation class CookieTest13 */14 @ WebServlet ("/CookieTest") 15 public class CookieTest extends HttpServlet {16 private static final long serialVersionUID = 1L; 17 18/*** 19 * @ see HttpServlet # HttpServlet () 20 */21 public CookieTest () {22 super (); 23 // TODO Auto-generated constructor stub24} 25 26/** 27 * @ see HttpServlet # doGet (HttpServletRequest request, HttpServletResponse response) 28 */29 protected void doGet (HttpServletRequest request, HttpServletResponse Response) throws ServletException, IOException {30 31 // store the Cookie object in the array 32 Cookie [] cookies = request. getCookies (); 33 if (cookies! = Null) {34 // traverse all Cookie objects 35 for (Cookie c: cookies) {36 // retrieve Cookie Object name 37 String name = c. getName (); 38 // get the Cookie object value 39 String value = c. getValue (); 40 // output the result to 41 response on the page. getWriter (). write (name + "=" + value); 42} 43} 44} 45 46}

Ii. Next we will introduce the application of the session.
1. HttpSession class: used to save session data
1) Create or obtain a session Object
HttpSession getSession ()
HttpSession getSession (boolean create)
2) set the session object
Void setMaxInactiveInterval (int interval): sets the session validity period.
Void invalidate (): destroys the session object.
Java. lang. String getId (): Obtain the session number.
3) Save session data to the session Object
Void setAttribute (java. lang. String name, java. lang. Object value): save data
Java. lang. Object getAttribute (java. lang. String name): Get Data
Void removeAttribute (java. lang. String name): clears data.
2. Session Principle
Problem: the server can identify different viewers !!!

Premise: In which session domain object stores data, You must retrieve it from which domain object !!!!
Browser 1: (assign a unique tag to s1: s001, send s001 to the browser)
1) create a session object and save session data
HttpSession session = request. getSession (); -- save session data s1
New window of browser 1 (s001 marked to the server for query, s001-> s1, return s1)
1) obtain the session data of the session Object
HttpSession session = request. getSession (); -- s1 can be retrieved

New browser 1: (s001 is not included, s1 cannot be returned)
1) obtain the session data of the session Object
HttpSession session = request. getSession (); -- s2 cannot be retrieved

Browser 2: (s001 is not included, s1 cannot be returned)
1) obtain the session data of the session Object
HttpSession session = request. getSession (); -- s3 cannot be retrieved
3. Sesson details
1) java. lang. String getId (): Get the session number.
2) Two getSession methods:
GetSession (true)/getSession (): Creates or obtains a session object. No matched session number. A new session object is automatically created.
GetSession (false): Get the session object. No matched session number. null is returned.
3) void setMaxInactiveInterval (int interval): sets the session validity period.
Session Object destruction time:
3.1 by default, servers are automatically reclaimed at 30 minutes.
3.2 modify the session recovery time
3.3 modify the session validity period globally

<! -- Modify the global validity period of a session: minutes -->
<Session-config>
<Session-timeout> 1 </session-timeout>
</Session-config>

Manually destroy the session object
Void invalidate (): destroys the session object.
4) how to avoid the loss of the browser's JSESSIONID cookie as the browser closes

/**
* Manually send a cookie stored on the hard disk to the browser
*/
Cookie c = new Cookie ("JSESSIONID", session. getId ());
C. setMaxAge (60*60 );
Response. addCookie (c );

4. The following is the code of the HttpSession application.

1 package com. vastsum; 2 3 import java. io. IOException; 4 import java. util. enumeration; 5 6 import javax. servlet. servletException; 7 import javax. servlet. annotation. webServlet; 8 import javax. servlet. http. httpServlet; 9 import javax. servlet. http. httpServletRequest; 10 import javax. servlet. http. httpServletResponse; 11 import javax. servlet. http. httpSession; 12 13/** 14 * Servlet implementation class Http SessionDemo15 */16 @ WebServlet ("/HttpSessionDemo") 17 public class HttpSessionDemo extends HttpServlet {18 private static final long serialVersionUID = 1L; 19 20/** 21 * @ see HttpServlet # HttpServlet () 22 */23 public HttpSessionDemo () {24 super (); 25 // TODO Auto-generated constructor stub26} 27 28/** 29 * @ see HttpServlet # doGet (HttpServletRequest request, HttpServletResponse response) 30 */31 protected Void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {32 // TODO Auto-generated method stub33 // sets the encoding 34 response. setContentType ("text/html; charset = UTF-8"); 35 // create HttpSession object 36 HttpSession httpSession = request. getSession (); 37 // set the value and content of HttpSession 38 httpSession. setAttribute ("name", "srv"); 39 httpSession. setAttribute ("phone", "051112345678"); 40 // Obtain the unique session id41 String sessionId = httpSession. getId (); 42 // get the value of the specified name 43 // String value = (String) httpSession. getAttribute ("name"); 44 45/*** get all values in HttpSession. The returned value is 47 x/48 Enumeration of Enumeration type <String> attributeNames = httpSession. getAttributeNames (); 49 50 while (attributeNames. hasMoreElements () {51 // traverse all name52 String name = (String) attributeNames in the session. nextElement (); 53 // find the value54 String value = (String) httpSession corresponding to the name. getAttribute (name); 55 // output to browser 56 response. getWriter (). write (name + "=" + value); 57} 58 if (httpSession. isNew () {59 response. getWriter (). write ("the session does not exist. The latest sessionId is:" + sessionId); 60} 61 else {62 response. getWriter (). write ("session already exists, and the sessionId is set to:" + sessionId); 63} 64 // set the object destruction time. The time granularity is minute 65 httpSession. setMaxInactiveInterval (1); 66} 67 68}

 

Related Article

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.