• 跟着江南一点雨学习springmvc(2)


    一、@SessionAttributes注解

            如果在类上加有@SessionAttributes注解,那么当在方法中的model参数设置对于的值时,该参数的值会自动存入session作用域中。

    1. package com.qfedu.demo.controller;
    2. import org.springframework.stereotype.Controller;
    3. import org.springframework.ui.Model;
    4. import org.springframework.web.bind.annotation.GetMapping;
    5. import org.springframework.web.bind.annotation.ResponseBody;
    6. import org.springframework.web.bind.annotation.SessionAttribute;
    7. import org.springframework.web.bind.annotation.SessionAttributes;
    8. import org.springframework.web.bind.support.SessionStatus;
    9. import javax.servlet.http.HttpSession;
    10. import java.util.Enumeration;
    11. @Controller
    12. //下面这个配置表示,将来请求接口中,如果将 name 和 age 存入到 model 中,则自动存入到 session 中
    13. @SessionAttributes({"name","age"})
    14. public class HelloController {
    15. @GetMapping("/hello")
    16. @ResponseBody
    17. public String hello(){
    18. return "hello";
    19. }
    20. /**
    21. * 注意,由于类上面添加了 @SessionAttributes 注解,所以接口方法中的 name 和 age 属性将会被自动存入到 HttpSession 中。
    22. * @param model
    23. */
    24. @GetMapping("/set")
    25. @ResponseBody
    26. public void set(Model model){
    27. model.addAttribute("name","lisi");
    28. model.addAttribute("age",22);
    29. model.addAttribute("gender","nan");
    30. }
    31. @GetMapping("/get")
    32. @ResponseBody
    33. public void get(HttpSession session){
    34. Enumeration attributeNames = session.getAttributeNames();
    35. while (attributeNames.hasMoreElements()){
    36. System.out.println(session.getAttribute(attributeNames.nextElement()));
    37. }
    38. }
    39. /**
    40. * @SessionAttribute("name") 表示从 HttpSession 中获取 key 为 name 的数据,并赋值给这里的 name 参数
    41. * @param name
    42. * @param age
    43. */
    44. @GetMapping("/get2")
    45. @ResponseBody
    46. public void get2(@SessionAttribute("name") String name,@SessionAttribute("age") Integer age){
    47. System.out.println("name = " + name);
    48. System.out.println("age = " + age);
    49. }
    50. @GetMapping("/clear")
    51. @ResponseBody
    52. public void clear(SessionStatus sessionStatus) {
    53. //清除通过 @SessionAttributes 注解存入到 session 中的数据
    54. //如果是自己手动存入到 HttpSession 中的数据,是不会被清除的
    55. sessionStatus.setComplete();
    56. }
    57. }

    二、springmvc中的Json

            在springmvc中目前主流使用的是Jackson(重点)、gsonfastjson(了解)这三种方式,其中Jackson和gson只要引入依赖就可以使用,fastjson需要手动配置才能使用。

    Jackson:

            下面先介绍Jackson的使用方法:首先是导入Jackson的依赖,然后就可以使用了,如果需要个性定制时间显示格式,需要在xml配置文件中设置相应的bean

    1. <dependency>
    2. <groupId>com.fasterxml.jackson.core<
  • 相关阅读:
    C 写的加密文件几个函数
    javaEE初阶---linux
    Leetcode——最长递增子序列
    HDLbits exercises 4 (MORE VERILOG FEATURES节选题)
    关于:未同意隐私政策,应用获取ANDROID ID问题
    权限系统--前后端分离
    Unload data from Databend | 新手篇(4)
    精度误差问题与eps
    Anaconda安装及配置(详细版)
    paddlenlp centos7镜像从0开始搭建
  • 原文地址:https://blog.csdn.net/qq_53884348/article/details/127076573