在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中方法 ...
随机推荐
- Linux修改服务器ip
Linux基础二(修改ip地址.修改网关.修改DNS服务器.重新启动网络配置) 网络的初始化 .ip地址的修改(临时生效) 使用ifconfig命令 ifconfig 网卡名 ip地址 netma ...
- tomcat优化总结【持续更新】
配置优化 <Connector port=" maxThreads=" URIEncoding="UTF-8" maxKeepAliveRequests= ...
- 解决方案:WindowsError: [Error 2]
使用Python的rename()函数重命名文件时出现问题,提示 WindowsError: [Error 2] 错误,最初代码如下: def renameFile(filename): filePr ...
- activemq依赖包获取
现在项目中使用的是activemq-all.jar的jar,17M多,里面集成了日志.spring等相关的包.但项目启动时发现系统使用的是activemq包中的日志实现,没有用本项目的日志包.只能将整 ...
- 【BZOJ】3971 [WF2013]Матрёшка
[算法]区间DP [题解] 参考写法:BZOJ 3971 Матрёшка 解题报告 第二个DP可以预处理mex优化到O(nM+n2),不过我懒…… 第一个DP有另一种写法:不预处理,在一个n2取出来 ...
- nyoj 15 括号匹配(二) (经典dp)
题目链接 描述 给你一个字符串,里面只包含"(",")","[","]"四种符号,请问你需要至少添加多少个括号才能使这些 ...
- vue清空input file
input file是只读的,给form一个id,用form.reset()干掉里面input的值 document.getElementById("uploadForm")&am ...
- ajax中datatype的json和jsonp
前言: 说到AJAX就会不可避免的面临两个问题,第一个是AJAX以何种格式来交换数据?第二个是跨域的需求如何解决?这两个问题目前都有不同的解决方案,比如数据可以用自定义字符串或者用XML来描述,跨域 ...
- Coursera在线学习---第十节.大规模机器学习(Large Scale Machine Learning)
一.如何学习大规模数据集? 在训练样本集很大的情况下,我们可以先取一小部分样本学习模型,比如m=1000,然后画出对应的学习曲线.如果根据学习曲线发现模型属于高偏差,则应在现有样本上继续调整模型,具体 ...
- 如何修改或美化linux终端
先丢一张效果图: 如何让您的 LD 的终端更具个性呢?首先,我们需要了解下面几点知识.A:配置文件 个人配置文件:~/.bashrc全局设定文件:/etc/bash.bashrc(修改需要管理员权限) ...