servlet Cookie使用方法详解(六)
本文实例为大家分享了servlet Cookie的使用方法,供大家参考,具体内容如下
1.cookie介绍
Cookie,指某些网站为了辨别用户身份、进行 session 跟踪而储存在用户本地终端上的数据(通常经过加密)。(可以叫做浏览器缓存)
2.cookie案例
servlet 源码
package com.learn; 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; import java.io.PrintWriter; /** * */ public class CookieServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //cookie引用 Cookie cookie = null; //设置返回类型为文本类型 resp.setContentType("text/plain"); //获取输出对象 PrintWriter out = resp.getWriter(); //从请求参数中获取cookies Cookie[] cookies = req.getCookies(); if(cookies != null){ for (int i = 0; i < cookies.length ; i++) { out.println("name:"+cookies[i].getName()); out.println("value:"+cookies[i].getValue()); //如果cookie值为user,则赋值给cookie if(cookies[i].getName().equals("user")){ cookie = cookies[i]; } } } else { out.print("no cookie"); } if(cookie == null){ cookie = new Cookie("user","tom"); //设置cookie最大值为60分钟 cookie.setMaxAge(60*60); resp.addCookie(cookie); } else if(cookie.getValue().equals("tom")){ cookie.setValue("jack"); resp.addCookie(cookie); } else if(cookie.getValue().equals("jack")){ cookie.setMaxAge(0); resp.addCookie(cookie); } out.close(); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { super.doPost(req, resp); } }
web,xml 配置
<servlet> <servlet-name>cookie</servlet-name> <servlet-class>com.learn.CookieServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>cookie</servlet-name> <url-pattern>/cookie</url-pattern> </servlet-mapping>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。
赞 (0)