从cookie中获取用户信息并添加到session

package com.sale.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;

import com.google.gson.Gson;
import com.sale.bean.T_MALL_USER;

@Controller
public class IndexController {

	public String index(HttpServletRequest request, HttpSession session) {
		Cookie[] cookies = request.getCookies();
		if (cookies != null) {
			String user_cookie = "";
			for (int i = 0; i < cookies.length; i++) {
				if ((cookies[i].getName()).equals("user_cookie")) {
					user_cookie = cookies[i].getValue();
				}
			}
			try {
				user_cookie = URLDecoder.decode(user_cookie, "utf-8");  //将cookie中获取的字符串进行解码,防止有中文
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			if (user_cookie != null && !user_cookie.equals("")) {
				T_MALL_USER user = new Gson().fromJson(user_cookie, T_MALL_USER.class);
				session.setAttribute("user", user);
			}

		}

		return "sale_index";
	}

}

 

你可能感兴趣的:(springmvc)