当前位置:网站首页>cookie_ session
cookie_ session
2022-07-24 07:14:00 【SJMP1974】
One 、cookie
Solve the problem of Chinese code disorder :
// solve post Request Chinese garbled code problem
// It must be called before the request parameter is obtained
req.setCharacterEncoding("UTF-8");
// Solve the problem of responding to Chinese random code
resp.setContentType("text/html; charset=UTF-8");
add to cookie, Save in browser :
In browser applicatioin Item can be viewed .
protected void createCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1 establish Cookie object
Cookie cookie = new Cookie("key4", "value4");
//2 Notify the client to save Cookie
resp.addCookie(cookie);
//1 establish Cookie object
Cookie cookie1 = new Cookie("key5", "value5");
//2 Notify the client to save Cookie
resp.addCookie(cookie1);
resp.getWriter().write("Cookie Create success ");
}
get cookie
protected void getCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Cookie[] cookies = req.getCookies();
for (Cookie cookie : cookies) {
// getName Method returns Cookie Of key( name )
// getValue Method returns Cookie Of value value
resp.getWriter().write("Cookie[" + cookie.getName() + "=" + cookie.getValue() + "] <br/>");
}
Cookie iWantCookie = CookieUtils.findCookie("key1", cookies);
// for (Cookie cookie : cookies) {
// if ("key2".equals(cookie.getName())) {
// iWantCookie = cookie;
// break;
// }
// }
// If not equal to null, Explain that the given value , That is to find what you need Cookie
if (iWantCookie != null) {
resp.getWriter().write(" I found what I needed Cookie");
}
}
Set up cookie Life time of
- The parameter is an integer , How many seconds does it survive
- Parameter is -1, Then the browser closes ,cookie Delete immediately
- Parameter is 0, Delete immediately
/** * Default session level Cookie * * @param req * @param resp * @throws ServletException * @throws IOException */
protected void defaultLife(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Cookie cookie = new Cookie("defalutLife", "defaultLife");
cookie.setMaxAge(-1);// Set the time to live
resp.addCookie(cookie);
}
Create with path Of cookie
protected void testPath(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Cookie cookie = new Cookie("path1", "path1");
// getContextPath() ===>>>> Get the engineering path
cookie.setPath(req.getContextPath() + "/abc"); // ===>>>> / Project path /abc
resp.addCookie(cookie);
resp.getWriter().write(" Created a system with Path The path of Cookie");
}
Use cookie Login without user name
package com.atguigu.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;
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String username = req.getParameter("username");
String password = req.getParameter("password");
if ("wzg168".equals(username) && "123456".equals(password)) {
// Sign in success
Cookie cookie = new Cookie("username", username);
cookie.setMaxAge(60 * 60 * 24 * 7);// At present Cookie Within one week
resp.addCookie(cookie);
System.out.println(" Sign in success ");
} else {
// Sign in Failure
System.out.println(" Sign in Failure ");
}
}
}
Two 、session
establish session
protected void createOrGetSession(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// Create and get Session Conversation object
HttpSession session = req.getSession();
// Judge At present Session conversation , Whether it is newly created
boolean isNew = session.isNew();
// obtain Session Unique identification of the session id
String id = session.getId();
resp.getWriter().write(" Got Session, its id yes :" + id + " <br /> ");
resp.getWriter().write(" This Session Is it a new creation :" + isNew + " <br /> ");
}
towards session Store data in the field
/** * Go to Session Save data in * * @param req * @param resp * @throws ServletException * @throws IOException */
protected void setAttribute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.getSession().setAttribute("key1", "value1");
resp.getWriter().write(" Has gone to Session Data is saved in ");
}
/** * obtain Session Data in domain * * @param req * @param resp * @throws ServletException * @throws IOException */
protected void getAttribute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Object attribute = req.getSession().getAttribute("key1");
resp.getWriter().write(" from Session Take out in key1 The data of :" + attribute);
}
session The default timeout length in 30mins, You can set
protected void defaultLife(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// Got Session Default timeout of
int maxInactiveInterval = req.getSession().getMaxInactiveInterval();
resp.getWriter().write("Session The default timeout of is :" + maxInactiveInterval + " second ");
}
protected void life3(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// First get Session object
HttpSession session = req.getSession();
// Set up current Session3 Seconds after timeout
session.setMaxInactiveInterval(3);
resp.getWriter().write(" At present Session Has been set to 3 Seconds after timeout ");
}
Set up session invalid
protected void deleteNow(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// First get Session object
HttpSession session = req.getSession();
// Give Way Session The session is about to time out
session.invalidate();
resp.getWriter().write("Session Has been set to timeout ( Invalid )");
}
3、 ... and 、 The browser and Session Technical insider of the relationship

The logic of logout is actually to get the requested session, Then disable it .
req.getSession().invalidate();
边栏推荐
- Redis 持久化
- baddy:核心函数入口
- 单点登录的三种实现方式
- 第二部分—C语言提高篇_3. 指针强化
- 17. What is the situation of using ArrayList or LinkedList?
- 单场GMV翻了100倍,冷门品牌崛起背后的“通用法则”是什么?
- 【LeetCode-简单】20. 有效的括号 - 栈
- (note sorting is not completed) [graph theory: find the shortest path of single source]
- Do you really know the judgement sentence?
- B. Also Try Minecraft
猜你喜欢

C语言中extern,static, register,volatile 关键字的作用;保姆级教学!

Part II - C language improvement_ 2. Memory partition

What kind of mode can make platform users self-help fission- Chain 2+1
![[USB voltmeter and ammeter] Based on stm32f103c8t6 for Arduino](/img/5f/40e4e144a628ef1aa38ab536b40366.png)
[USB voltmeter and ammeter] Based on stm32f103c8t6 for Arduino

One book a day: machine learning and practice -- the road to the kaggle competition from scratch

项目上线就炸,这谁受得了

重磅直播 | ORB-SLAM3系列代码讲解地图点(专题二)

Redis fragment cluster

Variables and data types (04) end

MongoDB应用场景及选型(海量数据存储选型)
随机推荐
Part II - C language improvement_ 4. Secondary pointer
Don't compare with anyone, just be yourself
17. What is the situation of using ArrayList or LinkedList?
Traditional e-commerce dividends disappear, how to enter the new social e-commerce?
处理树形结构数据
File “manage.py“, line 14 ) from exc ^ SyntaxError: invalid syntax出错的原因及解决方法
Flow control statement of avascript
The function of extern, static, register, volatile keywords in C language; Nanny level teaching!
单场GMV翻了100倍,冷门品牌崛起背后的“通用法则”是什么?
文件上传下载Demo
C language from entry to soil function
第二部分—C语言提高篇_3. 指针强化
【方向盘】IDEA的代码审查能力,来保证代码质量
9. Use grid technology to draw a Pentagon on the screen.
Accumulation of project problems
编译与调试(gcc,g++,gdb)
Basic syntax of MySQL DDL and DML and DQL
GDB debug core/dump
Decompress the anchor and enjoy 4000w+ playback, adding a new wind to the Kwai food track?
【Tips】创建版本控制项目的简单方法