cookie不支持中文,必须转码后存储,否则会乱码
Cookie ck = new Cookie("username", URLEncoder.encode(name, "UTF-8")); ck.setPath("/"); //设置cookie的路径,只有包含这个路径(以这个路径为前缀)的文件才能访问这个cookie ck.setMaxAge(Integer.MAX_VALUE); //设置cookie的最大保存时间 response.addCookie(ck);
jsp端访问cookie要解码
<script> window.onload = function(){ var username = document.getElementsByName("name")[0]; //获得用户名这个标签 //document.cookie = "path=/"; var name = decodeURIComponent("${cookie.username.value}"); //获取到名为username的cookie中转码后的值,若值不存在则为空串 username.value = name; if(name.length() >= 1){ var memName = document.getElementsByName("memName")[0]; memName.checked = true; } } </script>
EL表达式获取cookie的值:${cookie.username.name}, ${cookie.username.value}