后台设置Cookie值,前台进行获取
通过cookie取得用户的个性化信息
注意事项:1.中文的存在,需要进行utf-8的编码,之后再进行解码即可,避免乱码。
之所以 有时会用到 cookie.setPath("/");语句,是因为当你的SpringMVC的controller类上面有设置@RequestMapping("/User")
这样子,所以才会用到,没有就忽略它。
设置好cookie的保存时间
cookie.setMaxAge(60 * 60 * 24);
@RequestMapping("login")
public String goto_login(HttpServletResponse response, HttpSession session, T_MALL_USER_ACCOUNT user,
HttpServletRequest request, ModelMap map) {
// 登陆,远程用户认证接口
T_MALL_USER_ACCOUNT select_user = loginMapper.select_user(user);
if (select_user == null) {
return "redirect:/login.do";
} else {
session.setAttribute("user", select_user);
// 在客户端存储用户个性化信息,方便用户下次再访问网站时使用
try {
Cookie cookie = new Cookie("yh_mch", URLEncoder.encode(select_user.getYh_mch(), "utf-8"));
// cookie.setPath("/");
cookie.setMaxAge(60 * 60 * 24);
response.addCookie(cookie);
Cookie cookie2 = new Cookie("yh_nch", URLEncoder.encode("周润发", "utf-8"));
// cookie.setPath("/");
cookie2.setMaxAge(60 * 60 * 24);
response.addCookie(cookie2);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return "redirect:/index.do";
}
有两种方法获取cookie的值,一种是用服务器获取客户端的数据,然后把数据再返回给客户端。另一种是客户端直接获取(推荐这种,比较方便,而且如果选择服务端的话,每次只能返回一个页面,不实用)。
第一种(不推荐):
@RequestMapping("index")
public String index(HttpServletRequest request, ModelMap map) {
String yh_mch = "";
Cookie[] cookies = request.getCookies();
if(cookies != null && cookies.length > 0) {
for (int i = 0; i
第二种: 通过客户端cookie取得用户的个性化信息
decodeURIComponent是js自带的utf-8解码的函数
yh_nch=“你好”;yh_mm="123456"
获取的cookie字符串会出现 “空格”和 “;”,需要进行正则匹配,首先空格去除,然后再以 “;”进行分割,分割的数组再进行“=”分割获取所需要的值。yh_nch=“你好”