JavaWeb(七)——Cookie、Session

1. Session

Session : a user opens a browser, click a lot of hyperlinks, access to multiple web resources, close your browser, a process that can be called the session;
stateful session : a classmate came to the classroom, the classroom next time, we'll know the students had been there, called stateful session;

A website, how to prove you been?
The client - server

  • The server to the client a letter, Client Access server to bring the next letter on it; cookie
  • You came to the registration server the next time you come I'll match you; seesion

2. Save the session of the two technologies

cookie

  • Client technology (response request)

session

  • Server technology , the use of this technology, you can save the user's session information, we can put the information or data in the Session!

Common: website after login, you do not have to log on the next time, the second direct access will go up!

Detailed Description Example:
Here Insert Picture Description

3. Cookie

Here Insert Picture Description
(1) get the cookie information from the request

(2) The server responds to the client cookie

Cookie[] cookies = req.getCookies(); //获得Cookie
cookie.getName(); //获得cookie中的key
cookie.getValue(); //获得cookie中的vlaue
new Cookie("lastLoginTime", System.currentTimeMillis()+""); //新建一个cookie
cookie.setMaxAge(24*60*60); //设置cookie的有效期
resp.addCookie(cookie); //响应给客户端一个cookie

cookie: usually stored in the local user directory appdata;

A website cookie if there is an upper limit! Talk details

  • A Cookie can only save a message;
  • A web site can send multiple cookie to the browser, cookie store up to 20;
  • Cookie size is limited 4KB;
  • 300 browser cookie limit

Delete Cookie:

  • Do not set the validity period, close the browser, automatically lapse;
  • Expiration time set to 0;

Codec:
the URLEncoder.encode ( "handsome credits", "UTF-. 8")
URLDecoder.decode (cookie.getValue (), "UTF-. 8")

Test Case:

  • Create a file called CookieDemo01 in the java package
package com.zz.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

//保存用户上一次访问的时间
public class CookieDemo01 extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //服务器,告诉你,你来的时间,把这个时间封装成为一个 信件,你下带来,我就知道你来了
        //解决中文乱码
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");

        PrintWriter out = resp.getWriter();

        //Cookie,服务器端从客户端获取呀;
        Cookie[] cookies = req.getCookies(); //这里返回数组,说明Cookie可能存在多个

        //判断Cookie是否存在
        if (cookies!=null){
            //如果存在怎么办
            out.write("你上一次访问的时间是:");
            for (int i = 0; i < cookies.length; i++) {
                Cookie cookie = cookies[i];
                //获取cookie的名字
                if (cookie.getName().equals("lastLoginTime")){
                    //获取cookie中的值
                    long lastLoginTime = Long.parseLong(cookie.getValue());
                    Date date = new Date(lastLoginTime);
                    out.write(date.toLocaleString());

                }
            }
        }else {
            out.write("这是您第一次访问本站");
        }
        //服务给客户端响应一个cookie;
        Cookie cookie = new Cookie("lastLoginTime", System.currentTimeMillis()+"");
        //cookie有效期为1天
        cookie.setMaxAge(24*60*60);
        resp.addCookie(cookie);
    }


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

  • Registered in the web.xml file:
<servlet>
        <servlet-name>CookieDemo01</servlet-name>
        <servlet-class>com.zz.servlet.CookieDemo01</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>CookieDemo01</servlet-name>
        <url-pattern>/c1</url-pattern>
    </servlet-mapping>
  • Test results visit:
    Here Insert Picture Description

4. Session (Key)

Here Insert Picture Description

What is Session:

  • Server will give each user (browser) to create a Seesion objects;
  • A Seesion exclusively a browser, as long as the browser is not closed, the Session there;
  • After the user logs in, it can access the entire site! -> Save user information; save the cart information ......
    Here Insert Picture Description

Session and cookie difference:

  • Cookie is the user data addressed to the user's browser, the browser stores (store multiple);
  • Session data is written to the user's user exclusive Session, the server-side save (save important information, reduce waste server resources);
  • Session object is created by the server.

scenes to be used:

  • Save a user's login information;
  • Shopping Cart information;
  • Data is often used throughout the site, we store it in Session.

When Session created to do the following things:

  • Cookie cookie = new Cookie(“JSESSIONID”,sessionId); //创建cookie
  • resp.addCookie (cookie); // cookie response back to

(1) Create a Session:

session.setAttribute("name",new Person("帅币",17));
  • Create a file called SessionDemo01 in the java package:
package com.zz.servlet;

import com.zz.pojo.Person;

import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.IOException;

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("帅币",17));
        //获取Session的ID
        String sessionId = session.getId();

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

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

  • Registered in the web.xml file:
<servlet>
        <servlet-name>SessionDemo01</servlet-name>
        <servlet-class>com.zz.servlet.SessionDemo01</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>SessionDemo01</servlet-name>
        <url-pattern>/s1</url-pattern>
    </servlet-mapping>
  • Access test results:
    Here Insert Picture Description
    (2) to obtain the contents of Session:

     session.getAttribute("name");
    
  • Create a file called SessionDemo02 in the java package:

package com.zz.servlet;

import com.zz.pojo.Person;

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

public class SessionDemo02 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中存东西
        Person person = (Person) session.getAttribute("name");

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

    }

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

  • Registered in the web.xml file:
<servlet>
        <servlet-name>SessionDemo02</servlet-name>
        <servlet-class>com.zz.servlet.SessionDemo02</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>SessionDemo02</servlet-name>
        <url-pattern>/s2</url-pattern>
    </servlet-mapping>
  • Pojo create an entity class in java file
    Here Insert Picture Description
    Person in the code:
package com.zz.pojo;

public class Person {
    private String name;
    private int age;

    public Person() {
    }

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }


    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

  • Test results visit:
    Here Insert Picture Description
    Here Insert Picture Description

(3) manually logout Session

session.invalidate();
  • Create a file called SessionDemo03 in the java package:
package com.zz.servlet;

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

public class SessionDemo03 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        session.removeAttribute("name");
        //手动注销Session
        session.invalidate();
    }

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

  • Registered in the web.xml file:
<servlet>
        <servlet-name>SessionDemo03</servlet-name>
        <servlet-class>com.zz.servlet.SessionDemo03</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>SessionDemo03</servlet-name>
        <url-pattern>/s3</url-pattern>
    </servlet-mapping>
  • Test results visit:

Here Insert Picture Description
Here Insert Picture Description
Here Insert Picture Description

Not manually canceled, you can automatically set the expiration time in the session configuration web.xml:

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

Here Insert Picture Description

Published 62 original articles · won praise 2 · Views 2728

Guess you like

Origin blog.csdn.net/nzzynl95_/article/details/104236160