Cookie简单读写
程序员文章站
2024-03-20 14:03:58
...
读写实例:
package com.taray.controller;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
/**
* java.lang.IllegalArgumentException: Control character in cookie value or attribute.
* 该报错是由于这个中文的编码的问题中文采用的是unicode编码,而英文采用的是ASCII编码,
* 所以当COOkie保存中文的时候需要对中文进行编码,而且从Cookie中取出内容的时候也要进行解码,编码和解码可以使用
* URLEncoder.encode(request.getParameter("uname"),"utf-8"); 编码工具类
* URLDecoder.decode(cookie.getValue(),"utf-8") 解码工具类
*/
@Controller
@Scope("prototype")
public class CookieController {
@RequestMapping("index")
public ModelAndView cookieSetting(HttpServletRequest request,HttpServletResponse response){
ModelAndView res=new ModelAndView("/index");
//cookie取值
Cookie [] ck=request.getCookies();
if(ck!=null&&!"".equals(ck)){
for(Cookie cookie:ck){
//用户名
if(cookie.getName().equals("uname")){
try {
String str=cookie.getValue();
if(str!=null&&!"".equals(str)){
res.addObject("name", URLDecoder.decode(cookie.getValue(),"utf-8"));
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
//得分
if(cookie.getName().equals("uscore")){
res.addObject("score", cookie.getValue());
}
}
}
return res;
}
@RequestMapping("modify")
public String addCookie(HttpServletRequest request,HttpServletResponse response){
//cookie存值
String uname="";
try {
/**** 类URLEncoder
encode(String s)
已过时。 结果字符串可能因平台默认编码不同而不同。因此,改用 encode(String,String) 方法指定编码。
encode(String s, String enc)
使用指定的编码机制将字符串转换为 application/x-www-form-urlencoded 格式。 */
uname = URLEncoder.encode(request.getParameter("uname"),"utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String uscore=request.getParameter("uscore");
Cookie ck=new Cookie("uname", uname);
Cookie ck1=new Cookie("uscore", uscore);
//不设置cookie的maxage
ck.setMaxAge(60*60*24); //一天
ck1.setMaxAge(60*60*24); //一天
ck.setPath("/");
ck1.setPath("/");
response.addCookie(ck);
response.addCookie(ck1);
//return "forward:index.htm"; //转发
return "redirect:index.htm"; //重定向
}
}
index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<script type="text/javascript" src="http://apps.bdimg.com/libs/jquery/1.6.4/jquery.min.js"></script>
<link href="http://libs.baidu.com/bootstrap/2.3.2/css/bootstrap.min.css" rel="stylesheet">
<script src="http://libs.baidu.com/bootstrap/2.3.2/js/bootstrap.min.js"></script>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="<%=basePath %>modify.htm" method="post">
<input type="text" name="uname" value="${name }">
<input type="text" name="uscore" value="${score }">
<input type="submit" class="btn btn-success" value="submit">
</form>
</body>
</html>
package com.taray.controller;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class CookieUtil {
/**
* 设置cookie
* @param response
* @param name cookie名字
* @param value cookie值
* @param maxAge cookie生命周期 以秒为单位
*/
public static void addCookie(HttpServletResponse response,String name,String value,int maxAge){
Cookie cookie = new Cookie(name,value);
cookie.setPath("/");
if(maxAge>0) cookie.setMaxAge(maxAge);
response.addCookie(cookie);
}
/**
* 根据名字获取cookie
* @param request
* @param name cookie名字
* @return
*/
public static Cookie getCookieByName(HttpServletRequest request,String name){
Map<String,Cookie> cookieMap = ReadCookieMap(request);
if(cookieMap.containsKey(name)){
Cookie cookie = (Cookie)cookieMap.get(name);
return cookie;
}else{
return null;
}
}
/**
* 将cookie封装到Map里面
* @param request
* @return
*/
private static Map<String,Cookie> ReadCookieMap(HttpServletRequest request){
Map<String,Cookie> cookieMap = new HashMap<String,Cookie>();
Cookie[] cookies = request.getCookies();
if(null!=cookies){
for(Cookie cookie : cookies){
cookieMap.put(cookie.getName(), cookie);
}
}
return cookieMap;
}
}