Java Session session technology

1. Introduction to Session

Session technology is a technology that stores data on the server side. Each client creates a memory space to store customer data, but the client needs to carry an identification ID to the server to find its own memory space. Therefore, the implementation of Session is based on Cookie, and Session needs to use Cookie to store the customer's unique identifier JSESSIONID

Two, Session acquisition

1. Get the Session object

HttpSession session = request.getSession();

This method will obtain the Session object dedicated to the current session. If the server does not have a Session object for the session, a new Session will be created and returned. If there is already a Session belonging to the session, the existing Session will be returned directly (essentially, according to JSESSIONID Determine whether the client already has a Session on the server) 

3. Session access data & life cycle

1. How to access data from session (session is also a domain object), there are three methods as follows

session.setAttrbute(String name, Object obj);

session.getAttrbute(String name);

session.removeAttrbute(String name);

2. The life cycle of the Session object

  • Create: created when request.getSession() is executed for the first time
  • Destroy: session expires/invalidation 
    when the server (abnormally) shuts down (default 30 minutes)

Can be configured in the project's web.xml

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

4. Persistence of Session

Since the creation and acquisition of the Session is determined by the JSESSIONID in the Cookie, if the Cookie is cleared, the server cannot find the corresponding Session, so if you want to persist the Session, you must persist the JSESSIONID in the Cookie

Five, Java Servlet Session instance

1. Create Session

@WebServlet(name = "SessionServlet",urlPatterns = "/session")
public class SessionServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //第一次访问时没有session,服务器会自动创建一个session对象
        //之后再次访问的时候已经存在了session对象,这个直接获取这个对象
        HttpSession session = request.getSession();
        String sessionId = session.getId();
        response.getWriter().write("JESSIONID="+sessionId);


    }
}

2. Save Session

@WebServlet(name = "SaveSessionServlet",urlPatterns = "/saveSession")
public class SaveSessionServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        HttpSession session = request.getSession();

        //创建一个cookie覆盖之前服务器自动生成的JSESSIONID
        Cookie cookie = new Cookie("JSESSIONID", session.getId());
        //设置持久化时间
        cookie.setMaxAge(60*60);
        response.addCookie(cookie);


        session.setAttribute("goods","cup");

    }
}

3. Get Session

@WebServlet(name = "GetSessionServlet",urlPatterns = "/getSession")
public class GetSessionServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


        //获取session
        HttpSession session = request.getSession();


        String goods = (String) session.getAttribute("goods");

        response.getWriter().write(goods+"");

    }
}

6. Simple application of shopping cart 

1. Add to shopping cart

@WebServlet(name = "AddCartServlet",urlPatterns = "/addCart")
public class AddCartServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //1 获取到商品的信息
        String name = request.getParameter("name");
        // 2 需要保存商品信息到session
        HttpSession session = request.getSession();
        List list = (List) session.getAttribute("list");


        //第一次访问的时候list不存在,需要创建一个list
        if (list==null){
            list=new ArrayList();

        }
        list.add(name);

        session.setAttribute("list",list);
        // session的持久化操作,也就是持久化JSESSIONID
        Cookie cookie = new Cookie("JSESSIONID", session.getId());
        cookie.setMaxAge(60*60*24);
        cookie.setPath("/hello");
        response.addCookie(cookie);


    }
}

2. Front-end simple display

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<center>
	<h1>商品列表</h1>
	<a href="/hello/addCart?name=杯子">杯子</a><br>
	<a href="/hello/addCart?name=书包">书包</a><br>
	<a href="/hello/addCart?name=笔记本">笔记本</a><br>

</center>
</body>
</html>

3. Get shopping cart data

@WebServlet(name = "GetCartServlet",urlPatterns = "/getCart")
public class GetCartServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


        HttpSession session = request.getSession();

        List<String> list= (List<String>) session.getAttribute("list");
        response.setContentType("text/html;charset=utf-8");

        for (String s : list) {

            response.getWriter().write(s+"<br/>");

        }

    }
}

Guess you like

Origin blog.csdn.net/mshxuyi/article/details/131307093