目录
Cookie 是服务器通知客户端保存键值对的一种技术。客户端有了 Cookie 后,每次请求都发送给服务器。每个 Cookie 的大小不能超过 4kb

使用BaseServlet抽取Servlet对象,在请求中携带名称为action,值为方法名的参数动态调用请求方法。
- public abstract class BaseServlet extends HttpServlet{
- @Override
- protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- doPost(req,resp);
- }
-
- @Override
- protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- //解决请求中文乱码问题
- req.setCharacterEncoding("UTF-8");
- //解决响应中文乱码问题
- resp.setContentType("text/html; charset=UTF-8");
-
- //获取参数action的值
- String action=req.getParameter("action");
-
- try {
- // 匹配指定名称和参数的类的方法,此方法返回的是Method对象
- Method method = this.getClass().getDeclaredMethod(action, HttpServletRequest.class, HttpServletResponse.class);
- //调用目标业务方法,这里的 this 是子类
- method.invoke(this,req,resp);
- } catch (Exception e){
- e.printStackTrace();
- }
- }
- }
Servlet程序
- public class CookieServlet extends BaseServlet {
- protected void createCookie(HttpServletRequestreq,HttpServletResponse resp)throwsServletException, IOException {
- //1 创建 Cookie对象
- Cookie cookie = new Cookie("key4", "value4");
-
- //2 通知客户端保存 Cookie
- resp.addCookie(cookie);
-
- resp.getWriter().write("Cookie创建成功");
- }
- }
web.xml
- <servlet>
- <servlet-name>CookieServletservlet-name>
- <servlet-class>com.servlet.CookieServletservlet-class>
- servlet>
- <servlet-mapping>
- <servlet-name>CookieServletservlet-name>
- <url-pattern>/cookieServleturl-pattern>
- servlet-mapping>
请求地址:localhost:8080/13_cookie_session/cookieServlet?action=createCookie
解释:当请求到达CookieServlet,由于没有 doGet() 方法,会向父类寻找, BaseServlet中有 doGet()方法,调用父类的 doGet()方法,首先获取 action 的值createCoookie,这里的 this是子类,通过反射调用子类名为 createCookie 的方法。

Cookie的工具类:查找指定名称的 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;
- }
- }
- 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() + "]
"); - }
-
- Cookie iWantCookie = CookieUtils.findCookie("key3", cookies);
- if (iWantCookie != null) {
- resp.getWriter().write("找到了需要的Cookie");
- }
- }
- protected void updateCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletExcepton, IOException {
- Cookie cookie = new Cookie("key3","NewValue");
- resp.addCookie(cookie);
- }
- protected void updateCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- Cookie cookie1 = CookieUtils.findCookie("key3", req.getCookies());
- if(cookie1!=null){
- cookie1.setValue("newValue2");
- resp.addCookie(cookie1);
- }
- }

Cookie 的生命控制指的是如何管理 Cookie 什么时候被销毁(删除)
setMaxAge()
- protected void life3600(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
-
- Cookie cookie = new Cookie("life3600", "life3600");
- cookie.setMaxAge(60 * 60);
- resp.addCookie(cookie);
- resp.getWriter().write("已经创建了一个存活一小时的 Cookie");
- }
-
- protected void deleteNow(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- Cookie cookie = CookieUtils.findCookie("key3", req.getCookies());
-
- if(cookie!=null){
- cookie.setMaxAge(0);
- resp.addCookie(cookie);
- resp.getWriter().write("key3已删除");
- }
- }
-
- protected void defaultLife(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
-
- Cookie cookie = new Cookie("defalutLife","defaultLife");
- cookie.setMaxAge(-1);//设置存活时间
- resp.addCookie(cookie);
- resp.getWriter().write("默认的会话级别的Cookie");
- }
cookie.html
- html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
- <html>
- <head>
- <meta http-equiv="pragma" content="no-cache" />
- <meta http-equiv="cache-control" content="no-cache" />
- <meta http-equiv="Expires" content="0" />
- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
- <title>Cookietitle>
- <base href="http://localhost:8080/13_cookie_session/">
- <style type="text/css">
-
- ul li {
- list-style: none;
- }
-
- style>
- head>
- <body>
- <iframe name="target" width="500" height="500" style="float: left;">iframe>
- <div style="float: left;">
- <ul>
- <li><a href="cookieServlet?action=createCookie" target="target">Cookie的创建a>li>
- <li><a href="cookieServlet?action=getCookie" target="target">Cookie的获取a>li>
- <li><a href="cookieServlet?action=updateCookie" target="target">Cookie值的修改a>li>
- <li>Cookie的存活周期li>
- <li>
- <ul>
- <li><a href="cookieServlet?action=defaultLife" target="target">Cookie的默认存活时间(会话)a>li>
- <li><a href="cookieServlet?action=deleteNow" target="target">Cookie立即删除a>li>
- <li><a href="cookieServlet?action=life3600" target="target">Cookie存活3600秒(1小时)a>li>
- ul>
- li>
- <li><a href="cookieServlet?action=testPath" target="target">Cookie的路径设置a>li>
- <li><a href="" target="target">Cookie的用户免登录练习a>li>
- ul>
- div>
- body>
- html>
Cookie 的 path 属性可以有效的过滤哪些 Cookie 可以发送给服务器。哪些不发。
path 属性是通过请求的地址来进行有效的过滤。
请求地址如下:
http://ip:port/工程路径/a.html
http://ip:port/工程路径/abc/a.html
- protected void testPath(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- Cookie cookie = new Cookie("path1", "path1");
- // getContextPath() 得到工程路径
- cookie.setPath( req.getContextPath() + "/abc" );
-
- //访问http://localhost:8080/13_cookie_session/abc才能看到该cookie
- resp.addCookie(cookie);
-
- resp.getWriter().write("创建了一个带有 Path 路径的 Cookie");
- }

login.jsp 页面
- <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>
LoginServlet 程序
- 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("1".equals(username)&&"1".equals(password)){
- Cookie cookie = new Cookie("username", username);
- cookie.setMaxAge(60*60*24); //当前cookie一天有效
- resp.addCookie(cookie);
- System.out.println("登录成功");
- }else{
- System.out.println("登录失败");
- }
- }
- }
request.getSession()
isNew():判断到底是不是刚创建出来的(新的)
每个会话都有一个身份证号。也就是 ID 值。而且这个 ID 是唯一的。
- protected void createOrGetSession(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- HttpSession session = req.getSession();
-
- boolean isNew = session.isNew();
-
- String id = session.getId();
-
- resp.getWriter().write("得到的session的id是:"+id+"
"); - resp.getWriter().write("session是否是新创建的"+isNew+"
"); - }
- public class SessionServlet extends BaseServlet{
- protected void deleteNow(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
-
- protected void setAttribute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- req.getSession().setAttribute("key1", "value1");
- resp.getWriter().write("已经往 Session 中保存了数据");
- }
-
- protected void getAttribute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- Object attribute = req.getSession().getAttribute("key1");
- resp.getWriter().write("从 Session 中获取出 key1 的数据是:" + attribute);
- }
- }
- /*
- 设置Session的超时时间(以秒为单位),超过指定的时长,Session 就会被销毁。
- 值为正数的时候,设定 Sessio 的超时时长。
- 负数表示永不超时
- */
- public void setMaxInactiveInterval(int interval)
-
- //获取 Session 的超时时间
- public int getMaxInactiveInterval()
-
- //让当前 Session 会话马上超时无效。
- public void invalidate()
Session 默认的超时时间长为 30 分钟。
因为在 Tomcat 服务器的配置文件 web.xml 中默认有以下的配置,它就表示配置了当前 Tomcat 服务器下所有的 Session 超时配置默认时长为:30 分钟。
- <session-config>
- <session-timeout>30session-timeout>
- session-config>
如果说。你希望你的 web 工程,默认的 Session 的超时时长为其他时长。你可以在你自己的 web.xml 配置文件中做以上相同的配置。就可以修改你的 web 工程所有 Seession 的默认超时时长。
-
- <session-config>
- <session-timeout>20session-timeout>
- session-config>
如果你想只修改个别 Session 的超时时长。就可以使用上面的 API。
Session超时的概念介绍

- protected void deleteNow(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- HttpSession session = req.getSession();
- session.invalidate();
- resp.getWriter().write("Session 已经设置为超时(无效)");
- }
-
- protected void life3(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
-
- HttpSession session = req.getSession();
- session.setMaxInactiveInterval(3);
- resp.getWriter().write("当前 Session 已经设置为 3 秒后超时");
- }
session.html
- html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
- <html>
- <head>
- <meta http-equiv="pragma" content="no-cache" />
- <meta http-equiv="cache-control" content="no-cache" />
- <meta http-equiv="Expires" content="0" />
- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
- <title>Sessiontitle>
- <base href="http://localhost:8080/13_cookie_session/">
- <style type="text/css">
-
- ul li {
- list-style: none;
- }
-
- style>
- head>
- <body>
- <iframe name="target" width="500" height="500" style="float: left;">iframe>
- <div style="float: left;">
- <ul>
- <li><a href="sessionServlet?action=createOrGetSession" target="target">Session的创建和获取(id号、是否为新创建)a>li>
- <li><a href="sessionServlet?action=setAttribute" target="target">Session域数据的存储a>li>
- <li><a href="sessionServlet?action=getAttribute" target="target">Session域数据的获取a>li>
- <li>Session的存活li>
- <li>
- <ul>
- <li><a href="sessionServlet?action=defaultLife" target="target">Session的默认超时及配置a>li>
- <li><a href="sessionServlet?action=life3" target="target">Session3秒超时销毁a>li>
- <li><a href="sessionServlet?action=deleteNow" target="target">Session马上销毁a>li>
- ul>
- li>
- <li><a href="" target="target">浏览器和Session绑定的原理a>li>
- ul>
- div>
- body>
- html>
Session 技术,底层其实是基于 Cookie 技术来实现的。
