7、Cookie、Session
7.1、 conversation
conversation : The user opens a browser , Click a lot of hyperlinks , Visit multiple web resources , Close the browser , This process can be called conversation
Stateful conversation : A classmate came to the classroom , Come back to the classroom next time , We will know this classmate , I've been to , It's called stateful conversation ;
How can you prove that you are a student of Xikai ?
you Xikai
- invoice I'll give you an invoice
- School Registration Xikai marked that you were here
A website , How to prove you've been here ?
client Server side
- The server sends a letter to the client , The next time the client accesses the server, just bring a letter ;cookie
- The server registers that you've been here , Next time you come, I'll match you ;session
7.2、 Two techniques for saving a session
cookie
- Client technology ( Respond to , request )
session
- Server technology , Using this technology , Can save user session information ? We can put information or data in session in !
Common scenes : After the website logs in , You don't have to log in next time , The second visit went straight up !
7.3、Cookie
- Get... From the request cookie Information
- The server responds to the client
Cookie[] cookies = req.getCookies(); // get Cookie
cookie.getName(); // get cookie Medium key
cookie.getValue(); // get cookie Medium value
new Cookie("lastLoginTime", System.currentTimeMillis()+""); // Create a new one cookie
cookie.setMaxAge(24*60*60); // Set up cookie The validity of the
resp.addCookie(cookie); // The response gives the client a cookie
cookie: It is usually saved in the local user directory appdata;
A website cookie Whether there is an upper limit ! Talk about the details
- One Cookie Only one message can be saved ;
- One web Sites can send multiple cookie, At most 20 individual cookie
- Cookie There's a limit to the size 4kb
- 300 individual cookie Browser limit
Delete Cookie:
- Do not set the validity period , Close the browser , Automatic failure ;
- Set the validity period to 0;
Encoding and decoding :
URLEncoder.encode(" Qinjiang ","UTF-8")
URLDecoder.decode(cookie.getValue(), "UTF-8")
7.4、Session( a key )
What is? Session:
- The server will give every user ( browser ) Create a Session object ;
- One Session Monopolize a browser , As long as the browser is not closed , This Session There is a ;
- After the user logs in , It can access the whole website ! --> Save user information ; Save shopping cart information ......
Session and cookie The difference between :
- Cookie It is to write the user's data to the user's browser , Browser save ( You can save multiple )
- Session It is to write the user's data to the user for exclusive use Session in , Server side save ( Keep important information , Reduce the waste of server resources )
- Session Objects are created by the server ;
Use scenarios :
- Save the information of a login user ;
- Shopping cart information ;
- Throughout the site , Frequently used data , We keep it in Session in ;
Use Session:
public class SessionDemo01 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// Solve the mess
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
// obtain Session
HttpSession session = req.getSession();
// to Session Deposit things in
session.setAttribute("name",new Person(" Qinjiang ",1));
// obtain Session Of ID
String sessionId = session.getId();
// Judge Session Is it newly created
if (session.isNew()){
resp.getWriter().write("session Create success ,ID:"+sessionId);
}else {
resp.getWriter().write("session It already exists in the server ,ID:"+sessionId);
}
//Session What did you do when you created it :
Cookie cookie = new Cookie("JSESSIONID", sessionId);
resp.addCookie(cookie);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
==========================================
// obtain Session
HttpSession session = req.getSession();
Person person = (Person) session.getAttribute("name");
System.out.println(person.toString());
==========================================
HttpSession session = req.getSession();
session.removeAttribute("name");
// Manual logout Session
session.invalidate();
Session expires automatically :web.xml To configure
<!-- Set up Session Default expiration time -->
<session-config>
<!--15 Minutes later Session Automatic failure , In minutes -->
<session-timeout>15</session-timeout>
</session-config>