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提供了内嵌的支持方案:

  1. 将数据缓存到session
    对Controller使用org.springframework.web.bind.annotation.SessionAttributes注解,可以将指定名称 或者 类型的数据,在model.addAttribute( String key,  Object value)时,缓存到session中。
  2. 清除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. 1. 处理静态资源 2. controller如何接受请求得参数 3. 如何把controller得数据保存到view. 4. 在controller如何完成重定向到指定路径 5. controller返回json数据

    1. 1. 处理静态资源2. controller如何接受请求得参数3. 如何把controller得数据保存到view.4. 在controller如何完成重定向到指定路径5. controller ...

  2. [python]mysql数据缓存到redis中 取出时候编码问题

    描述: 一个web服务,原先的业务逻辑是把mysql查询的结果缓存在redis中一个小时,加快请求的响应. 现在有个问题就是根据请求的指定的编码返回对应编码的response. 首先是要修改响应的bo ...

  3. 在scrapy中将数据保存到mongodb中

    利用item pipeline可以实现将数据存入数据库的操作,可以创建一个关于数据库的item pipeline 需要在类属性中定义两个常量 DB_URL:数据库的URL地址 DB_NAME:数据库的 ...

  4. 将数据缓存到sessionStorage中

    //获取侧边栏 if (sessionStorage.getItem(`${env}${empId}leftMenu`)) { const leftMenu = JSON.parse(sessionS ...

  5. json和xml封装数据、数据缓存到文件中

    一.APP的通信格式之xml xml:扩展标记语言,可以用来标记数据,定义数据类型,是一种允许用户对自己标记语言进行定义的源语言.XML格式统一,扩平台语言,非常适合数据传输和通信,业界公认的标准. ...

  6. ASP.NET MVC中将数据从Controller传递到视图

    ASP.NET MVC中将数据从Controller传递到视图方法 1.ViewData ViewData的类型是字典数据,key-value 如:ViewData["Data"] ...

  7. Spring与Hibernate集成中的Session问题

    主要讨论Spring与Hibernate集成中的session问题 1.通过getSession()方法获得session进行操作 public class Test extends Hibernat ...

  8. Spring官网阅读(十七)Spring中的数据校验

    文章目录 Java中的数据校验 Bean Validation(JSR 380) 使用示例 Spring对Bean Validation的支持 Spring中的Validator 接口定义 UML类图 ...

  9. Spring MVC 前后台数据交互

    本文是转载文章,感觉比较好,如有侵权,请联系本人,我将及时删除. 原文网址地址:<Spring MVC 前后台数据交互> 1.服务端数据到客户端 (1)返回页面,Controller中方法 ...

随机推荐

  1. js addDays ,addYears

    //添加天 Date.prototype.addDays = function (d) { this.setDate(this.getDate() + d); }; //添加周 Date.protot ...

  2. 【STSRM10】数学上来先打表

    [算法]DP+数学计数 [题意]给出n个点(不同点之间有区别),求出满足下列条件的连边(双向边)方案(对1004535809取模): 1.每条边连接两个不同的点,每两个点之间至多有一条边. 2.不存在 ...

  3. Android通知栏介绍与适配总结

    由于历史原因,Android在发布之初对通知栏Notification的设计相当简单,而如今面对各式各样的通知栏玩法,谷歌也不得不对其进行更新迭代调整,增加新功能的同时,也在不断地改变样式,试图迎合更 ...

  4. SQL SERVER 常用公式

    SQL SERVER 获取当前月的天数 SELECT -DAY(getdate()+-DAY(getdate())) SQL server 除法计算百分比[整数乘1.0否则结果为0或1] CONVER ...

  5. crontab 详解 -- (转)

    cron 是一个可以用来根据时间.日期.月份.星期的组合来调度对重复任务的执行的守护进程. cron 假定系统持续运行.如果当某任务被调度时系统不在运行,该任务就不会被执行. 要使用 cron 服务, ...

  6. face_recognition 人脸识别报错

    [root@localhost examples]# python facerec_from_video_file.py RuntimeError: module compiled against A ...

  7. Centos_Lvm expand capacity without restarting CentOS

    Rescan the new disk(/dev/sdb): #ls /sys/class/scsi_host/ host0 host1 host2 [root@db210_13:56:14 /dat ...

  8. spark 环境搭建坑

    spark的新人会有什么坑 spark是一个以java为基础的,以Scala实现的,所以在你在安装指定版本的spark,需要检查你用的是对应spark使用什么版本的scala,可以通过spark-sh ...

  9. sicily 数据结构 1014. Translation

    Description You have just moved from Waterloo to a big city. The people here speak an incomprehensib ...

  10. 【LabVIEW技巧】LabVIEW OOP怎么学

    前言 有很多人对LabVIEW OOP存在比较极端的看法,大致分为两类: 1. 绝对否定派认为LabVIEW OOP只不过是LabVIEW为了追求时髦,在面向过程的基础上用簇做了一些特性,实际上完全不 ...