本文实例为大家分享了servlet Cookie的使用方法,供大家参考,具体内容如下
1.cookie介绍
Cookie,指某些网站为了辨别用户身份、进行 session 跟踪而储存在用户本地终端上的数据(通常经过加密)。(可以叫做浏览器缓存)
2.cookie案例
servlet 源码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
|
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 配置
1
2
3
4
5
6
7
8
|
< 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 > |
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:http://www.cnblogs.com/wwyx-xi/p/7594355.html