JavaWeb study notes 20/10/23Session

Session (emphasis)

What is Session:

Insert picture description here

  • The server will create a Session object for each user (browser)

  • A session occupies a browser, as long as the browser is not closed, the session will exist

  • After the user logs in, the entire website can be accessed! –> Save user information; save shopping cart information...

The difference between Session and cookie:

  • Cookie is to write the user's data to the user's browser, and the browser saves it (you can save multiple)
  • Session writes the user's data to the user's exclusive session and saves it on the server side (saves important information to reduce waste of server resources)
  • Session object is created by the server

scenes to be used:

  • Save the information of a logged-in user
  • Shopping cart information
  • Data that is frequently used throughout the website, we save it in the Session

Use Session:

public class SessionDemo01 extends HttpServlet {
    
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    

        //解决乱码问题
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=utf-8");

        //得到Session
        HttpSession session = req.getSession();

        //给Session中存东西
        session.setAttribute("name",new Person("家明","1"));

        //获取Session的ID
        String sessionId = session.getId();

        //判断Session是不是新创建
        if (session.isNew()){
    
    
            resp.getWriter().write("Session创建成功,ID:"+sessionId);
        }else {
    
    
            resp.getWriter().write("Session已经在服务器中存在了,ID:"+sessionId);
        }

        //Session创建的时候做了什么事情;
            //  Cookie cookie = new Cookie("JSESSIONID",sessionId);
            //  resp.addCookie(cookie);

    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        doGet(req, resp);
    }

}

//得到Session
HttpSession session = req.getSession();

Person person = (Person) session.getAttribute("name");

System.out.println(person.toString());

HttpSession session = req.getSession();
session.removeAttribute("name");

//手动注销Session
session.invalidate();

The session automatically expires (configured in web.xml):

<!--设置Session默认的失效时间-->
<session-config>
    <!--15分钟后Session自动失效,以分钟为单位-->
    <session-timeout>15</session-timeout>
</session-config>

Insert picture description here

Guess you like

Origin blog.csdn.net/qq_44685947/article/details/109249046