Cookie
A technique in which the server notifies the client to save key-value pairs.
Cookies are generated by the Servlet program and sent to the browser to save, and then sent to the server each time the browser sends a request.
Cookie values can uniquely identify the client. Its size is fixed at no more than 4KB.
The following examples are under the Cookiesession module of IDEA
Create a cookie
protected void createCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Cookie cookie = new Cookie("key1"."value1");
resp.addCookie(cookie);
resp.getWriter().write("Cookie added successfully");
}
Copy the code
Server obtains cookies
protected void getCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Cookie[] cookies = req.getCookies();
for (Cookie cookie : cookies) {
resp.getWriter().write("cookie["+cookie.getName()+"="+cookie.getValue()+"] <br/>");
}
Cookie iwantCookie = javautil.findCookie("key1",cookies); // Get the utility class for the specified cookie
if(iwantCookie ! =null){
resp.getWriter().write("Find the cookie you want"); }}Copy the code
public class javautil {
public static Cookie findCookie(String name, Cookie[] cookies){
if(name==null || cookies==null || cookies.length==0) {return null;
}
for (Cookie cookie : cookies) {
if(name.equals(cookie.getName()))
return cookie;
}
return null; }}Copy the code
Modify the cookie
The principle is to overwrite the original cookie. For cookies that have been modified or newly added, remember resp. AddCookie to take effect
protected void updateCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
/ / method
Cookie cookie = new Cookie("key1"."newvalue1");
resp.addCookie(cookie);
/ / method 2
Cookie[] cookies = req.getCookies();
Cookie findCookie = javautil.findCookie("key1", cookies);
if(findCookie! =null){
findCookie.setValue("newvalue2"); resp.addCookie(findCookie); }}Copy the code
Cookie life cycle
SetMaxAge () : Time in parentheses, in seconds
A positive value indicates that the data will be deleted after the specified time
Negative value: deletes when the browser is closed, which is the same as the session life cycle
0: deletes the file immediately without waiting
The valid path path is set
Path is an attribute of cookies that filters which cookies are sent to the server and which are not, based on the requested address.
Example:
Cookie1 path=/ Project path
Cookie2 path=/ Project path/ABC
Now that the browser sends a request to the address http://ip:port/ project path, Cookie1 will send it to the server, but Cookie2 will not.
Both Cookie1 and cookie2 are sent to the server if a request is sent to the address http://ip:port/ project path/ABC.
Set the path property of the cookie
protected void testPath(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Cookie cookie = new Cookie("key2"."value2");
cookie.setPath(req.getContextPath()+"/abc");
resp.addCookie(cookie);
}
Copy the code
Users do not need to enter login instances
Thinking figure
-
The login. The JSP page
<body> <form action="http://localhost:8080/cookiesession_war_exploded/login" method="get"> User name: <input type="text" name="username" value="${cookie.username.value}"> Password: <input type="password" name="password"> <input type="submit" value="Login"> </form> </body> Copy the code
-
The Login Servlet class
public class Login extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String username = "hsh"; String password = "123"; if (username.equals(req.getParameter("username")) && password.equals(req.getParameter("password"))){ Cookie username1 = new Cookie("username", username); username1.setMaxAge(60*60*24*7); resp.addCookie(username1); System.out.println("User name added to cookie"); }else{ System.out.println("Login failed"); }}}Copy the code
-
Configure the Login class in web.xml
After a successful login, the second login is automatically added to the user name
Session
A Session is an interface (HttpSession).
A session is the session, the technology used to maintain the association between the browser and the server, stored on the server side.
Each client has its own Session Session. It is usually used to save the information of the user after login.
Create and get sessions
Methods involved:
request.getSession() // The first call is to create the session, and the second call is to get
isNew() // Is the current session newly created
getId() // Get the id of the current session
Copy the code
Get data from session
Session is domain data
getSession().setAttribute("key1"."value1") // Add data to session
getSession().getAttribute("key1") // Get session data
Copy the code
Session Timeout Control
Session timeout refers to the maximum interval between two requests, which will be destroyed. Tomcat takes 30 minutes by default, which can be changed in web.xml
session.getMaxInactiveInterval() // Get the timeout period
session.setMaxInactiveInterval(60*60*24); // Set the timeout period
session.invalidate(); // Session is destroyed directly
Copy the code
Principle of the session
Cookie contains a pair of name values that store the JSESSION and Sessionid, which identify the session. That is, sessions are implemented based on cookies.