通过Request对象对cookie的设置、获取


<html>
<head></head>
<body>

<%
 request.setCharacterEncoding("UTF-8");
 String user = URLEncoder.encode(request.getParameter("user"),"UTF-8");
 Cookie cookie = new Cookie("zwqCookie",user+"#"+new java.util.Date().toString());
 cookie.setMaxAge(60*60*24*30);
 response.addCookie(cookie);
%>
 <script type = "text/javasript">window.location.href="index.jsp"</script>
</body>
</html>

 通过request对象将获得的user值使用UTF-8编码后,与日期一起拼接成一个cookie,并设置cookie的最大有效期为30天,然后通过Response回送cookie到浏览器

使用script脚本代码来让浏览器回到index主页

 在主页执行如下代码

<%
  Cookie cookie = request.getCookie();
  String user = "";
  String date = "";
  if(cookie!=null){
       for(int i=0;i<cookie.length;i++){
       if(cookie[i].getName().equals(zwqCookie)){
         user = URLDecoder.decode(cookies[i].getValue().split("#")[0],"UTF-8");
<!--在这里应该指定字符集为UTF-8否则不能得到中文下的user-->date = cookie[i].getValue().split("#")[0]; } } } %>

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM