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

本文介绍了一个基于Java Spring MVC框架的用户登录状态管理实现,通过Cookie存储用户信息并利用Gson进行序列化和反序列化,同时使用Session保存用户状态,确保了用户的登录信息在不同请求间的持久性和安全性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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";
	}

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值