JavaEE base (04): Session tracking technology, Session and Cookie Detailed

This article Source: GitHub · Click here || GitEE · Click here

First, session tracking

1, scene description

For example, log on to a shopping site, after a successful identification, the site operating under a single payment, etc. These operations currently logged in user information must be shared, so that the results of these operations the user can log in and make associations.

2, the concept Introduction

Can be understood as an interactive session between the client and the server, an interaction may contain multiple requests and responses. In JavaWeb, issue from the client to the server to start the first request, the session began, until the client closes the browser session ends. A plurality of shared data in a session request, which is session tracking technology.

Two, Cookie usage Detailed

1, Cookie Profile

In HTTP Cookie typically used to identify the user identity, for the data stored on the user's local terminal session tracking, usually encrypted, by the user of the client computer information either temporarily or permanently stored. The structure is a key and a value thereof. Sent to the client browser with the server's response. Then the client browser will save up Cookie, next time again to access the server and then the Cookie sent to the server.

Cookie is created by the server, and then sent to key clients by responding right. The client will save Cookie, Cookie and will mark the source of. When the client makes a request to the server will Cookie included in the request sent to the server so that the server can identify the client.

2, Cookie usage

  • Create a Cookie

JavaWeb, you can create a Cookie-based Servlet, and set the properties.

public class CookieServletOne extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        // 创建Cookie
        Cookie cookie = new Cookie("author","cicada");
        // 设置生命周期 1小时
        cookie.setMaxAge(60*60);
        response.addCookie(cookie) ;
        response.getWriter().print("Hello:Cookie");
    }
}

access:http://localhost:6002/cookieServletOne

View Response Headers:

Response Header
Set-Cookie: author=cicada; Max-Age=3600;

In this way, the server creates a Cookie got the client.

  • Get Cookie
public class CookieServletOne extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        System.out.println("doPost...");
        Cookie[] cookies = request.getCookies() ;
        for (Cookie cookie:cookies){
            System.out.println("Name:"+cookie.getName());
            System.out.println("Value:"+cookie.getValue());
        }
        response.setContentType("text/html;charset=utf-8");
        String userName = request.getParameter("userName") ;
        response.getWriter().print("Hello:"+userName);
    }
}

Through testing, the console Name:author;Value:cicadaoutput: .

  • Update Cookie

Update refers to covered Cookie, if the server sends duplicate Cookie then overwrites the original Cookie.

public class CookieServletTwo extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        // 创建Cookie
        Cookie cookie = new Cookie("author","smile");
        // 设置生命周期 2小时
        cookie.setMaxAge(60*60*2);
        response.addCookie(cookie) ;
        response.getWriter().print("Hello:Cookie");
    }
}

Cookie results may be obtained by the above method of testing.

  • Delete Cookie

cookie.setMaxAge (0): Life is equal to 0 is a special value that represents the cookie is invalid.

public class CookieServletTwo extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        Cookie[] cookies = request.getCookies() ;
        for (Cookie cookie:cookies){
            if (cookie.getName().equals("author")){
                cookie.setMaxAge(0);
                response.addCookie(cookie);
            }
        }
        String userName = request.getParameter("userName") ;
        response.getWriter().print("Hello:"+userName);
    }
}

So get re-tested method of Cookie, Cookie was found to remove the above is no.

3, Cookie related API

  • setMaxAge()

Setting cookie expiration time, in seconds. By default cookie will only be valid in the current session session.

  • getMaxAge()

Obtain the maximum lifetime of the cookie.

  • getName()

Get the name of the cookie. Name can not be changed after it is created.

  • getValue()

Gets the value associated with the cookie.

  • setValue(String value)

Set value value associated with the cookie. The same name set more than once would be covered.

Three, Session Tracking

1, Session Introduction

Session management, when users jump between Web page application variables are stored in the Session object will not be lost, but always exist throughout the user session. Servlet can save the need to share data within a session object to HttSession. Four domain objects: PageContext, ServletRequest, HttpSession, ServletContext.

2, Session operating principle

  • first time using

The first time you use the session, the server-side to create a session, session is stored on the server side, the data is stored in the session, sessionId sent to the client by Cookie, and exists only in the browser this session, which means that if the user closes the browser, then the Cookie is lost.

  • Client Access

When the Client Access server again, the request will bring sessionId, the server will find the corresponding session through sessionId, without having to create a new session.

  • Timeliness

When a session for a long time nobody used, the server will delete the session, when this configuration in Tomcat is a long 30 minutes can /conf/web.xml find this configuration in $ {CATALANA}, can also be a web.xml in covering this configuration!

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

3, the relevant API usage

  • getSesssion()

The current session already exists less direct return session object if the current session does not exist, create a session object and returns.

  • getAttribute(String name)

Returns the object that session session with the specified name.

  • getId()

A unique string assigned to the session identifier of the session.

  • setAttribute(String name,Object value)

With the specified name to bind an object to the session session.

  • removeAttribute(String name)

Specify the name of the object is removed from the session session.

4. Applications

In the website, it is often a visible feature is the last login time, and is based on Session can be very easy to achieve.

public class SessionServletOne extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        HttpSession session = request.getSession(true) ;
        Date createTime = new Date(session.getCreationTime());
        Date lastAccessTime = new Date(session.getLastAccessedTime());
        session.setAttribute("author","cicada");
        response.getWriter().print(
                "SessionId:" + session.getId() + "<br/>"+
                "User Author:" + session.getAttribute("author")+"<br/>"+
                "Create Time:" + dateFormat.format(createTime)+"<br/>"+
                "Last Access Time:"+dateFormat.format(lastAccessTime));
    }
}

accesshttp://localhost:6002/sessionServletOne

Printed page, many visits to see the effect.

SessionId:40C12C367CBFA7469D57E72C5C091300
User Author:cicada
Create Time:2019-12-14 15:34:10
Last Access Time:2019-12-14 15:35:13

Fourth, the source address

GitHub·地址
https://github.com/cicadasmile/java-base-parent
GitEE·地址
https://gitee.com/cicadasmile/java-base-parent

Guess you like

Origin www.cnblogs.com/cicada-smile/p/12047240.html