Article Directory
1. Cookie❤️
1. The concept of cookies
(1).Cookie translates to the meaning of biscuit.
(2).Cookie is a technology for 服务器
notifying 客户端
and saving . (3).After the client has a cookie, each request is sent to the server. (4).Each cookie The size cannot exceed 4kb.键值对
2. Create cookies
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
Cookie cookie = new Cookie("key1","value1");
resp.addCookie(cookie);
resp.getWriter().write("Cookie创建成功");
}
3. Get cookies
The server only needs one line of code to obtain the client's Cookie:req.getCookies():Cookies[]
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
Cookie[] cookies = req.getCookies();
Cookie iwantCookie = CookieUtils.findCookie("key1", cookies);
// for(Cookie cookie : cookies){
//getName()返回Cookie的key名
// getValue()返回Cookie的Value值
//resp.getWriter().write("Cookie[" + cookie.getName() + "=" + cookie.getValue() + "]");
//if("key1".equals(cookie.getName())){
// iwantCookie = cookie;
// break;
// }
// }
if (iwantCookie != null) {
resp.getWriter().write("找到了需要的cookie");
}
}
public class CookieUtils {
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;
}
}
4. Modify the value of the cookie
Solution 1:
(1). First create a Cookie object with the same name to be modified
(2). In the constructor, assign a new Cookie value at the same time
(3). Call resp.addCookie(Cookie);
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
Cookie cookie = new Cookie("key1", "newvalue1");
resp.addCookie(cookie);
resp.getWriter().write("key1已经修改好了");
}
Solution 2:
(1). First find the Cookie object that needs to be modified
(2). Call the setValue() method to assign a new Cookie value
(3). Call response.addCookie() to notify the client to save the modification
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
Cookie cookie = CookieUtils.findCookie("key1", req.getCookies());
if(cookie != null){
cookie.setValue("newvalue2");
resp.addCookie(cookie);//有些特殊符号例如,各种括号不支持,需要使用BASE64编码
}
resp.getWriter().write("key1已经修改好了");
}
5. Cookie life cycle control
The life control of the cookie refers to how to manage when the cookie is destroyed (deleted)
setMaxAge()
正数
, which means that it will expire after a specified number of seconds
负数
, which means that the cookie will be deleted after the browser is closed,
零
which means that the cookie will be deleted immediately
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Cookie cookie = new Cookie("de3","de1");
//cookie.setMaxAge(-1);
//cookie.setMaxAge(0);
cookie.setMaxAge(10);
resp.addCookie(cookie);
}
6.Cookie effective path Path setting
Cookies path属性
can effectively filter which cookies can be sent to 服务器
and which ones are not.
The path attribute is 请求的地址
used for effective filtering .
For example:
CookieA——path=/工程路径
CookieB——path=/工程路径/abc
the request address is as follows:
http://ip:port/工程路径/a.html
CookieA sends
CookieB and does not send
http://ip:port/工程路径/abc/a.html
CookieA sends
CookieB
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
Cookie cookie = new Cookie("path1","path1");
//getContextPath()得到工程路径
cookie.setPath(req.getContextPath() + "/abc");
resp.addCookie(cookie);
resp.getWriter().write("创建了一个带有工程路径的Cookie");
}
7. No need to enter user name to log in
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form action="http://localhost:8080/13_cookie_session/loginServlet" method="get">
用户名: <input type="text" name="username" value="${cookie.username.value}"><br>
密码: <input type="password" name="password" ><br>
<input type="submit" value="登录">
</form>
</body>
</html>
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String username = req.getParameter("username");
String password = req.getParameter("password");
if("wzg".equals(username) && "123456".equals(password)){
//登录成功
Cookie cookie = new Cookie("username", username);
cookie.setMaxAge(60*60*24*7);//当前Cookie一周内有效
resp.addCookie(cookie);
System.out.println("登录成功");
}else{
System.out.println("登录失败");
}
}
2.Session❤️
1. The concept of session
(1).Session is a 接口
(HttpSession)
(2).Session is a technology 会话
used to maintain a client and server (3). Each client has its own (4).Session session In, we often use the information after the user logs in关联
Session会话
保护
2. Session creation and acquisition
注意:
Create and get the Session, the API used is the same.
request.getSession():
Create or get the Session object
第一次调用:
to create a Session session
以后的调用:
and get the previously created Session session objectisNew():
Judging whether it is just created (new)
true
indicates that it has just been created
false
, indicating that it was created before obtaining注意:
Each session has its own ID, and this ID is unique
getId()
Get the session id value of the Session
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
//创建和获取Session会话对象
HttpSession session = req.getSession();
//判断 当前Session会话,是否是新创建出来的
boolean isNew = session.isNew();
//获取Session会话的唯一标识 id
String id = session.getId();
resp.getWriter().write("得到的Session,它的id是:" + id + "<br/>");
resp.getWriter().write("这个Session是否是新创建的:" + isNew + "<br/>");
}
3. Access to Session domain data
数据的存储
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
req.getSession().setAttribute("key1","value1");
resp.getWriter().write("已经往Session中保存了数据");
}
数据的获取
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
Object attribute = req.getSession().getAttribute("key1");
resp.getWriter().write("从Session中获取出key1的数据是: " + attribute);
}
4. Session life cycle control
public void setMaxInactiveInterval(int interval)
作用:
Set the session timeout (以秒为单位
), if the specified time is exceeded, the session will be destroyedpublic void getMaxInactiveInterval()
作用:
Get the session timeout
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
//获取了Session的默认超时时长
int maxInactiveInterval = req.getSession().getMaxInactiveInterval();
resp.getWriter().write("Session的默认超时时长为:" + maxInactiveInterval + "秒");
}
The above code can understand: Session's默认超时时间为30分钟
- We can find your own
web.xml文件
, and then change所有
the default timeout period of the web project Session.
<session-config>
<session-timeout>20</session-timeout>
</session-config>
- If you want to change the timeout period of individual Sessions, you can use the above API to set them individually
session.setMaxInactiveInterval(int interval)
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
//先获取Session对象
HttpSession session = req.getSession();
//设置当前Session3秒后超时
session.setMaxInactiveInterval(3);
//判断 当前Session会话,是否是新创建出来的
boolean isNew = session.isNew();
resp.getWriter().write("当前Session已经设置为3秒后超时"+ "<br/>");
resp.getWriter().write("这个Session是否是新创建的:" + isNew + "<br/>");
}
注意:
When the value 正数
is , set the session timeout time
When 负数
the value is , it means never timeout (rarely used)
public void invalidate()
作用:
Make the current Session session timeout immediately invalid
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
//先获取Session对象
HttpSession session = req.getSession();
//让当前Session马上超时
session.invalidate();
//判断 当前Session会话,是否是新创建出来的
boolean isNew = session.isNew();
resp.getWriter().write("当前Session已经设置为马上超时"+ "<br/>");
resp.getWriter().write("这个Session是否是新创建的:" + isNew + "<br/>");
}
5. The technical insider of the association between the browser and the Session
Session技术,底层其实是基于Cookie技术来实现的