亲宝软件园·资讯

展开

servlet Cookie使用方法 servlet Cookie使用方法详解(六)

柳暗花明睡一觉 人气:0
想了解servlet Cookie使用方法详解(六)的相关内容吗,柳暗花明睡一觉在本文为您仔细讲解servlet Cookie使用方法的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点: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>

加载全部内容

相关教程
猜你喜欢
用户评论