public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//取得 cookies
Cookie[] cookies=request.getCookies();
if(cookies!=null){
for(Cookie cookie :cookies){
System.out.println(cookie.getName()+":"+cookie.getValue());
}
}
else{
System.out.println("不存在 cookie ");
}
Cookie cookie=new Cookie("c", "123");
cookie.setMaxAge(60*60*24);//设置失效时间,注意这里如果设置的值为 0 ,则进行的是删除操作
response.addCookie(cookie);
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Cookie[] cookies=request.getCookies();
if(cookies != null){
for(Cookie cookie :cookies){
System.out.println(cookie.getName()+":"+cookie.getValue());
if("cn".equals((cookie).getName())){
String cnValue=URLDecoder.decode(cookie.getValue(),"UTF-8");
System.out.println(cnValue);
}
}
}
else{
System.out.println("没有 cookie ");
}
//Cookie cookie=new Cookie("cn","中文");//这样直接写中文是错误的
String value="中文";
String returnValue=URLEncoder.encode(value,"UTF-8");
Cookie cookie=new Cookie("cn",returnValue);
response.addCookie(cookie);
}
//编码
String data="中文";
String cnData1=URLEncoder.encode(data,"UTF-8");
//解码
String cnData2=URLDecoder.decode(cnData1,"UTF-8");
//手动编码
byte[] cnData3=data.getBytes("UTF-8");
StringBuffer buf=new StringBuffer();
for(int i=0;i
tomcat 会自动创建一个会话级cookie,浏览器关闭就没了
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session=request.getSession();
System.out.println(session.isNew());//是新创建的还是访问的以前
System.out.println(session.getId());
//持久化 session
Cookie cookie=new Cookie("JSESSIONID",session.getId());
cookie.setMaxAge(60*30);//设置失效时间30分钟
response.addCookie(cookie);
System.out.println(cookie);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session=request.getSession();
System.out.println("url:"+session.getId());
String url="DemoSessionServlet";
//URL 重写 ,可以做到如果禁用了cookie时类似在地址栏写入jsessionid 的作用
url=response.encodeURL(url);//如果不加这一句,并且浏览器禁用了cookie , 那么下面的连接将会新创建一个 sessionid,但是如果使用了这一句,那么这句话会将URL 重写,将当前页面的sessionid 传递给 下面连接的页面,也就是说连接后的 sessionid 和当前页面的sessionid 是相同的,如果浏览器没有禁用cookie ,那么URL 将不会发生改变
PrintWriter out=response.getWriter();
out.print("demosession");
}