标签:decode text code 基本使用 删除cookie 默认值 strong ted lan
public class MyServletA extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=utf-8");
Cookie cookie = new Cookie("name", URLEncoder.encode("张三", "utf-8"));
cookie.setMaxAge(1000);
resp.getWriter().write("服务器返回了Cookie!");
resp.addCookie(cookie);
}
}
public class MyServletB extends HttpServlet {
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=UTF-8");
resp.getWriter().write("服务器拿到Cookie:");
Cookie[] cookies = req.getCookies();
for (Cookie cookie : cookies) {
String name = cookie.getName();
resp.getWriter().write(name + "------" + URLDecoder.decode(cookie.getValue(), "utf-8") + " ");
}
}
}
通过setMaxAge(int expiry)进行设置
setPath(String uri),只有该资源路径才能获取Cookie
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=utf-8");
Cookie[] cookies = req.getCookies();
if(cookies==null){
resp.getWriter().write("第一次访问!");
}else{
resp.getWriter().write("上次访问时间:");
for (Cookie cookie : cookies) {
if ("previousTime".equals(cookie.getName())) {
System.out.println(cookie.getValue());
resp.getWriter().write(URLDecoder.decode(cookie.getValue(),"utf-8"));
break;
}
}
}
SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String time = simpleDateFormat.format(new Date());
String encode = URLEncoder.encode(time,"utf-8");
Cookie cookie=new Cookie("previousTime",encode);
resp.addCookie(cookie);
}
注意事项:
Cookie cookie=new Cookie(String name,String value)的value值中不能包含特殊字符,包括分号(;)、逗号(,)、等号(=)以及空格( )等。如果有特殊符号,则会报500
解决方案:
方案1. 如上: 先进行URLEncoder.encode(str,"utf-8"),在URLDecoder.decode(str,"utf-8")
方案2. 使用resp.setHeader("Set-Cookie","name=tom")
标签:decode text code 基本使用 删除cookie 默认值 strong ted lan
原文地址:https://www.cnblogs.com/kwdlh/p/12638587.html