Cookie:Session

Study after Cookie, solve the problem of sharing data without sending the request. Cookie is a browser-side data storage technology, this lesson focuses on an important additional data storage technology, session technology.

 

Session Learning

 

problem:

Request object to solve the problem of data sharing within different Servlet first request, then deal with the different requests a user needs to use the same data how to do it?

 

solve:

Use session technology.

 

principle:

The first user uses the browser sends a request to the server, the server after receiving the request, invoke corresponding Servlet processing. Will process the user creates a session object, used to store common data processing related to the user request, and session JSESSIONID this object in the Cookie stored (temporarily stored, i.e., failure of the browser is closed) in the browser. When a user initiates a second request and the subsequent request, the request message will be included with the JSESSIONID, server upon receiving the request, the corresponding Servlet invocation request process, and returns the corresponding session object according JSESSIONID.

 

Features:

Session Cookie art technology is dependent on server-side data storage technology.

Created by the server

Each user has a separate session

The default storage time is 30 minutes Role:

Solve the problem of different data sharing request of a user.

 

use:

Creating Session object

Data stored in the session object acquisition session object

Obtain data from the session object

If the acquired data session does not exist returns null.

 

note:

They do not close the browser, and in the case of the session does not fail, any user with a request acquired at any Servlet project are the same session object.

 

Scope: a conversation

 

Servlet Session

HTTP is a "stateless" protocol, which means retrieving the page each time the client, the client opens a separate connection to the Web server, the server will automatically retain no record prior to client requests.

 

Three ways to maintain session conversation between the Web client and Web server

1、Cookies

2, hidden form fields

3, URL rewrite

 

 

HttpSession object

In addition to the above-mentioned three methods, the Servlet also provides HttpSession interface that provides the user identifying the user and storing information about a plurality of page request when a cross mode or visit.

 

Servlet container to use this interface to create a session conversation between an HTTP client and HTTP server. Session lasts a specified period of time, across multiple connected or page request.

 

By calling () to get the public HttpSession object HttpServletRequest method getSession, as follows:

 

HttpSession session = request.getSession();

 

 

You need to call before sending any document content to the client request.getSession (). Here is a summary of several important methods HttpSession object available in:

 

Method and Description

public Object getAttribute(String name)

This method returns the object with the specified name of the session in the session, if the object name is not specified, null is returned.

 

public Enumeration getAttributeNames()

This method returns an enumeration of String objects, String object containing the names of all bound to the session session object.

 

public long getCreationTime()

The method returns the time session session is created, self GMT January 1970 date of midnight, in milliseconds.

 

public String getId()

The method returns to the assigned comprising a unique string identifier of the session of the session.

 

public long getLastAccessedTime()

This method returns the client sends the last session session-related requests time from GMT January 1970 date of midnight, in milliseconds.

 

public int getMaxInactiveInterval()

This method returns the Servlet container holding the maximum time interval sessions open session when the client access, in seconds.

 

public void invalidate()

This indicates that the method is invalid session session, and releasing bound to any object above it.

 

public boolean isNew()

If the client does not know the session session, or if the customer chooses not to participate the session into a session, then the method returns true.

 

public void removeAttribute(String name)

The method from session to remove the name of the specified object session.

 

public void setAttribute(String name, Object value)

This method uses the specified name to bind an object to the session session.

 

public void setMaxInactiveInterval(int interval)

In the process before indicating that the session is invalid session Servlet container, the time between the specified client request, in seconds.

 

 

Delete Session session data

1, to remove a specific attribute: You can call the public void removeAttribute (String name) method to remove a particular value associated with a key.

2, delete the entire session session: You can call the public void invalidate () method to discard the whole session to session.

3, set the session session expiration time: You can call the public void setMaxInactiveInterval (int interval) method to set up a separate session session timeout.

 

web.xml Configuration

Using a Tomcat, in addition to the above-described methods, you can configure the session in the session timeout web.xml file, as follows:

 

 <session-config>

    <session-timeout>15</session-timeout>

  </session-config>

 

 

 

Examples of the above timeout time is minutes, covering the Tomcat default timeout for 30 minutes.

 

In one getMaxInactiveInterval Servlet in () method returns a session timeout session, in seconds. Therefore, if the session configuration web.xml session timeout time of 15 minutes, then getMaxInactiveInterval () returns 900.

 
 
package cn.sxt;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class lianxi2
 */
@WebServlet("/lianxi2")
public class lianxi2 extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public lianxi2() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        response.getWriter().append("Served at: ").append(request.getContextPath());
       //创建Session 对象
        HttpSession session = request.getSession();
       //存储数据到session 对象(临时,关闭浏览器后就清空)
        session.setAttribute("name", "cxk");
        session.setAttribute ( "Age", "20 is" );
         // in response to the browser 
        . response.getWriter () the println ( "SECC" );
    
    
    
    
    
    
    
    
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}
 
 

 



package
cn.sxt; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; /** * Servlet implementation class lianxi1 */ @WebServlet("/lianxi1") public class lianxi1 extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public lianxi1() { super(); // TODO Auto-generated constructor stub } / ** * @see HttpServlet # doGet (Request the HttpServletRequest, HttpServletResponse the Response) * / protected void doGet (Request the HttpServletRequest, HttpServletResponse the Response) throws ServletException, IOException { // TODO Auto-Generated Method, Stub response.getWriter (). The append ( " ": Served aT ) .append (request.getContextPath ()); // same browser (the same user) the session objects the HttpSession session = ; Request.getSession () // objects which returns with the specified name in the conversation session . response.getWriter () the println ( "\ n-" + session.getAttribute ( "name") + "\ n-" ); response.getWriter().println("\n"+session.getAttribute("age")+"\n"); . response.getWriter () the println ( "\ n-" session.getCreationTime + () + "\ n-" ); // String This method returns a session including the session assigned to the unique identifier. . response.getWriter () println ( "\ the n-" + session.getId () + "\ the n-" ); // The last time the method returns the client sends a request to the time associated with the session session from 1970 GMT date of midnight on January 1, in milliseconds. . response.getWriter () the println ( "\ n-" session.getLastAccessedTime + () + "\ n-" ); // the Servlet container holding method returns the maximum time interval sessions open session when the client access, in seconds . . response.getWriter () println ( "\ the n-" + session.getMaxInactiveInterval () + "\ the n-" ); // This method will remove the session session to specify the name of the object. session.removeAttribute ( "age"This method indicates that the session before the session is invalid in the Servlet container, the time between the specified client request, in seconds. session.setMaxInactiveInterval (10 ); // change the attribute value session.setAttribute ( "name", "yCy" ); response.getWriter().println("\n"+session.getAttribute("name")+"\n"); response.getWriter().println("\n"+session.getAttribute("age")+"\n"); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }

 

Guess you like

Origin www.cnblogs.com/406070989senlin/p/11025177.html