实现会话跟踪技术方式:
两者之间的区别:
cookie是存储在浏览器中的
session是存储在服务器中的
对于cookie的操作主要分为两大类,分别是发送cookie和获取cookie
Cookie cookie = new Cookie(“key”,“value”);
javax.servlet javax.servlet-api 3.1.0 provided javax.servlet.jsp jsp-api 2.2 provided jstl jstl 1.2 taglibs standard 1.1.2 org.apache.tomcat.maven tomcat7-maven-plugin 2.2response.addCookie(cookie)
案例:
(1)创建Maven项目cookie-demo,并在pom.xml添加依赖
8
8
(2)编写Servlet类,名称为AServlet
@WebServlet(“/aServlet”)
public class AServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
(3)在Servlet中创建Cookie对象,存入数据,发送给前端
@WebServlet(“/aServlet”)
public class AServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//发送Cookie
//1. 创建Cookie对象
Cookie cookie = new Cookie(“username”,“zs”);
//2. 发送Cookie,response
response.addCookie(cookie);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
4)启动测试,在浏览器查看Cookie对象中的值
访问http://localhost:8080/cookie-demo/aServlet
chrome浏览器查看Cookie的值
选中打开开发者工具或者 使用快捷键F12 或者 Ctrl+Shift+I
Cookie[] cookies = request.getCookies();
cookie.getName();
cookie.getValue();
在BServlet中使用request对象获取Cookie数组,遍历数组,从数据中获取指定名称对应的值
@WebServlet("/bServlet")
public class BServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取Cookie
//1. 获取Cookie数组
Cookie[] cookies = request.getCookies();
//2. 遍历数组
for (Cookie cookie : cookies) {
//3. 获取数据
String name = cookie.getName();
if("username".equals(name)){
String value = cookie.getValue();
System.out.println(name+":"+value);
break;
}
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
启动测试,在控制台打印出获取的值
访问`http://localhost:8080/cookie-demo/bServlet