在Spring Controller中将数据缓存到session
Servlet方案
在Controller的方法的参数列表中,添加一个javax.servlet.http.HttpSession类型的形参。spring mvc会 自动把当前session对象注入这个参数,此后可以使用setAttribute(String key, Object value)将数据缓存到session,使用removeAttribute( String key)将指定的数据从session缓存中移除。
package cn.sinobest.jzpt.demo.login.web;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* 登陆相关Controller.<br>
* H - HttpSession.
* @author lijinlong
*
*/
@Controller
@RequestMapping("demo/h_login")
public class HLoginController { @RequestMapping("/login")
public String login(Model model, String username, HttpSession session) {
Logger.logger.debug("in HLoginController.login...");
String currUsername = session.getAttribute("username") == null ? null
: session.getAttribute("username").toString();
// 尝试从session中获取username数据。 boolean usernameIsNull = username == null || username.isEmpty();
boolean currunIsNull = currUsername == null || currUsername.isEmpty();
if (usernameIsNull && currunIsNull) {
return View.VIEW_LOGIN;
} if (!usernameIsNull) {
session.setAttribute("username", username);
// 将username缓存到session中。
}
return View.VIEW_LOGOUT;
} /**
* 注销.
* @param model
* @param session
* @return
*/
@RequestMapping("/logout")
public String logout(Model model, HttpSession session) {
Logger.logger.debug("in HLoginController.logout...");
session.removeAttribute("username");
// 将username从session中移除。
return View.VIEW_LOGIN;
}
}
LoginController.java
Spring方案
spring mvc提供了内嵌的支持方案:
- 将数据缓存到session
对Controller使用org.springframework.web.bind.annotation.SessionAttributes注解,可以将指定名称 或者 类型的数据,在model.addAttribute( String key, Object value)时,缓存到session中。 - 清除session中的数据
调用org.springframework.web.bind.support.SessionStatus实例的setComplete(),在方法的参数列表中声明SessionStatus类型的参数,会被自动注入。
package cn.sinobest.jzpt.demo.login.web;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;
/**
* 登陆相关Controller.<br>
* S - Spring Session.
* @author lijinlong
*
*/
@Controller
@RequestMapping("demo/s_login")
@SessionAttributes("username") // 指定了key为username的数据,会被放入session中。
public class SLoginController {
@RequestMapping("/login")
public String login(Model model, String username) {
Logger.logger.debug("in SLoginController.login...");
String currUsername = model.asMap().get("username") == null ? null
: model.asMap().get("username").toString();
// 尝试从session中获取username(spring mvc会自动把session中的数据装载到model中)。 boolean usernameIsNull = username == null || username.isEmpty();
boolean currunIsNull = currUsername == null || currUsername.isEmpty();
if (usernameIsNull && currunIsNull) {
return View.VIEW_LOGIN;
} if (!usernameIsNull) {
model.addAttribute("username", username);
// username会被放入session中(key和@SessionAttributes的参数匹配)。
}
return View.VIEW_LOGOUT;
} @RequestMapping("/logout")
public String logout(SessionStatus status,
@ModelAttribute("username") String currUsername) {
Logger.logger.debug("in SLoginController.logout...");
Logger.logger.debug("current user is:" + currUsername);
status.setComplete();
// 清除session中的attribute
return View.VIEW_LOGIN;
}
}
LoginController
SessionAttributes的使用方法
- 匹配单一的key
@SessionAttributes("username") // 匹配key=username的数据 - 匹配key数组
@SessionAttributes({"username", "password"}) // 匹配key=username或者password的数据 匹配单一类
@SessionAttributes(types=String.class) // 匹配String类型的数据- 匹配类数组
@SessionAttributes(types={String.class, List.class}) // 匹配String类型或List类型的数据 - 混合匹配
@SessionAttributes(value={"username", "password"}, types={String.class, List.class})
ModelAttribute
使用ModelAttribute,可以自动将session中指定的参数注入到方法的形参;但是如果session中没有指定的参数,会抛出异常:
org.springframework.web.HttpSessionRequiredException: Session attribute 'username' required - not found in session
Model中的数据
Spring 会把Session中的数据装载到Model中,所以使用model.asMap().get("username")可以获取 session中的数据。返回页面前,spring会把Model中的数据放入requestScope,所以在页面可以使 用${requestScope.username}来获取数据。
在Spring Controller中将数据缓存到session的更多相关文章
- 1. 处理静态资源 2. controller如何接受请求得参数 3. 如何把controller得数据保存到view. 4. 在controller如何完成重定向到指定路径 5. controller返回json数据
1. 1. 处理静态资源2. controller如何接受请求得参数3. 如何把controller得数据保存到view.4. 在controller如何完成重定向到指定路径5. controller ...
- [python]mysql数据缓存到redis中 取出时候编码问题
描述: 一个web服务,原先的业务逻辑是把mysql查询的结果缓存在redis中一个小时,加快请求的响应. 现在有个问题就是根据请求的指定的编码返回对应编码的response. 首先是要修改响应的bo ...
- 在scrapy中将数据保存到mongodb中
利用item pipeline可以实现将数据存入数据库的操作,可以创建一个关于数据库的item pipeline 需要在类属性中定义两个常量 DB_URL:数据库的URL地址 DB_NAME:数据库的 ...
- 将数据缓存到sessionStorage中
//获取侧边栏 if (sessionStorage.getItem(`${env}${empId}leftMenu`)) { const leftMenu = JSON.parse(sessionS ...
- json和xml封装数据、数据缓存到文件中
一.APP的通信格式之xml xml:扩展标记语言,可以用来标记数据,定义数据类型,是一种允许用户对自己标记语言进行定义的源语言.XML格式统一,扩平台语言,非常适合数据传输和通信,业界公认的标准. ...
- ASP.NET MVC中将数据从Controller传递到视图
ASP.NET MVC中将数据从Controller传递到视图方法 1.ViewData ViewData的类型是字典数据,key-value 如:ViewData["Data"] ...
- Spring与Hibernate集成中的Session问题
主要讨论Spring与Hibernate集成中的session问题 1.通过getSession()方法获得session进行操作 public class Test extends Hibernat ...
- Spring官网阅读(十七)Spring中的数据校验
文章目录 Java中的数据校验 Bean Validation(JSR 380) 使用示例 Spring对Bean Validation的支持 Spring中的Validator 接口定义 UML类图 ...
- Spring MVC 前后台数据交互
本文是转载文章,感觉比较好,如有侵权,请联系本人,我将及时删除. 原文网址地址:<Spring MVC 前后台数据交互> 1.服务端数据到客户端 (1)返回页面,Controller中方法 ...
随机推荐
- HDU2031 进制转换
#include <iostream> #include "string" #include "cstdio" #include "cst ...
- 2015/9/4 Python基础(8):映射和集合类型
Python里唯一的映射类型是字典.映射类型对象里,hash值(key)和指向的对象(值)是一对多的关系.字典对象是可变的,这一点上很像列表,它也可以存储任意个数任意类型的Python对象,其中包括容 ...
- Flume入门——Selector、Chanel等
1.selector (http://blog.csdn.net/looklook5/article/details/40430965) (http://blog.csdn.net/xiao_jun_ ...
- MyBatis注解Annotation介绍及Demo
MyBatis注解Annotation介绍及Demo 2014-04-21 17:09:55 标签:Mybatis Annotation 注解 ResultMap SqlBuilder 原创作品,允 ...
- Moq 和 RhinoMocks
我们在做单元测试的时候,利用mock可轻松构建出测试需要的类或接口,而不需要编写繁琐的测试代码. .net 下我知道Moq与Rhino Mocks这两个框架. Moq 网上介绍的比较多. Rhino ...
- socket 极值数量
在做Socket 编程时,我们经常会要问,单机最多可以建立多少个 TCP 连接,本文将介绍如何调整系统参数来调整单机的最大TCP连接数. Windows 下单机的TCP连接数有多个参数共同决定,下面一 ...
- quick 用系统浏览器打开url
需求描述: 在我们的游戏里面增加一个链接,直接用浏览器打开,进入到对应网站,进行一些支付活动. 解决: 于是我去百度了一下,发现了这篇文章,http://blog.csdn.net/teng_onth ...
- php中的parse_ini_file函数
作用:parse_ini_file() 函数解析一个配置文件,并以数组的形式返回其中的设置 格式:parse_ini_file(file,true)// (第二个参数为可选参数.如果设置为 true, ...
- Django【进阶】数据库查询性能相关
之前项目中没有考虑过数据库查询关于效率的问题,如果请求量大,数据庞大,不考虑性能的话肯定不行. tips:如图之前我们遇到过,当添加一张表时,作为原来表的外键,要给个默认值,现在我们写null ...
- vue-实现倒计时功能
JavaScript 创建一个 countdown 方法,用于计算并在控制台打印距目标时间的日.时.分.秒数,每隔一秒递归执行一次. msec 是当前时间距目标时间的毫秒数,由时间戳相减得到,我们将以 ...