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对。

  • 相关阅读:
    20200630(A--E)题解 by 王文硕
    20200629(A--E)题解 by 章思航
    GC垃圾回收
    Codeforces Round #629 (Div. 3) A、B、C
    AtomicInteger的Increment方法的自己实现。
    两个线程,一个输出字母一个输出数字,输出A1B2C3....Z26
    NIO记录
    mysql优化相关
    一些Nginx的Linux命令和conf配置文件
    docker记录
  • 原文地址:https://www.cnblogs.com/cielosun/p/6741246.html
Copyright © 2011-2022 走看看