zoukankan      html  css  js  c++  java
  • SpringMVC SessionAttributes 简述

    使用SpringMVC时,我们会发现网络上有关SessionAttributes注解的内容非常少,更多的人甚至推荐你继续用HttpServletRequest中的session管理方法来控制Session,这对于我这种能用注解连配置文件都不会去用的人来说太不优雅了。所以简单讲讲怎么用。

    在Controller类上,可以加标签来控制,使该类支持SessionAttributes,具体例子如下:

    @SessionAttributes("accountNumber")
    public class UserController {
        //Something
    }
    

    如果有多个值想存入session,则需这样调用:

    @SessionAttributes({"accountNumber","userDevice"})
    

    加入标签后,当你在方法中将key为"userId"的内容添加到model中时,该key-value对就会进入session,如下,在该例子中,我们从收到的信息中解析出accountNumber添加到model中,此时,该key-value对被添加到session中。

        @RequestMapping(value = "login", method = RequestMethod.POST)
        public String login(@RequestBody String mapString, Model model) throws Exception {
            //Something
            model.addAttribute("accountNumber", accountNumber);
            //Something
        }
    

    如果我们想调用该session中值,有两种方法:

    • 从model参数中获取。
    • 使用@ModelAttribute(key)的方法去获取。

    这里就第二个用法举例:

        @RequestMapping("display")
        public String display(@ModelAttribute("accountNumber") String accountNumber) throws Exception {
            //Something
            UserEntity userEntity = userService.findByAccountNumber(accountNumber);
            //Something
        }
    

    在使用了@ModelAttribute标签后,我们可以获取model中已经存有的来自session的这组key-value对。

  • 相关阅读:
    hdu 2151 Worm (DP)
    .NET中使用switch和java不一样的地方。
    逻辑运算符||和| 、&&和&的区别
    赋值表达式也有值
    交换两个变量的值(面试题)
    .NET中的 枚举
    .NET FrameWork 中的 CTS
    .NET中变量的类型问题
    .NET中的标识符、关键字 以及 .NET中的命名规范
    .NET中的注释种类,单行注释、多行注释、文档注释。。。
  • 原文地址:https://www.cnblogs.com/cielosun/p/6741246.html
Copyright © 2011-2022 走看看