如果在类上加有@SessionAttributes注解,那么当在方法中的model参数设置对于的值时,该参数的值会自动存入session作用域中。
- package com.qfedu.demo.controller;
-
- import org.springframework.stereotype.Controller;
- import org.springframework.ui.Model;
- import org.springframework.web.bind.annotation.GetMapping;
- import org.springframework.web.bind.annotation.ResponseBody;
- import org.springframework.web.bind.annotation.SessionAttribute;
- import org.springframework.web.bind.annotation.SessionAttributes;
- import org.springframework.web.bind.support.SessionStatus;
-
- import javax.servlet.http.HttpSession;
- import java.util.Enumeration;
-
- @Controller
- //下面这个配置表示,将来请求接口中,如果将 name 和 age 存入到 model 中,则自动存入到 session 中
- @SessionAttributes({"name","age"})
- public class HelloController {
- @GetMapping("/hello")
- @ResponseBody
- public String hello(){
- return "hello";
- }
-
- /**
- * 注意,由于类上面添加了 @SessionAttributes 注解,所以接口方法中的 name 和 age 属性将会被自动存入到 HttpSession 中。
- * @param model
- */
- @GetMapping("/set")
- @ResponseBody
- public void set(Model model){
- model.addAttribute("name","lisi");
- model.addAttribute("age",22);
- model.addAttribute("gender","nan");
- }
-
- @GetMapping("/get")
- @ResponseBody
- public void get(HttpSession session){
- Enumeration
attributeNames = session.getAttributeNames(); - while (attributeNames.hasMoreElements()){
- System.out.println(session.getAttribute(attributeNames.nextElement()));
- }
- }
- /**
- * @SessionAttribute("name") 表示从 HttpSession 中获取 key 为 name 的数据,并赋值给这里的 name 参数
- * @param name
- * @param age
- */
- @GetMapping("/get2")
- @ResponseBody
- public void get2(@SessionAttribute("name") String name,@SessionAttribute("age") Integer age){
- System.out.println("name = " + name);
- System.out.println("age = " + age);
- }
-
-
- @GetMapping("/clear")
- @ResponseBody
- public void clear(SessionStatus sessionStatus) {
- //清除通过 @SessionAttributes 注解存入到 session 中的数据
- //如果是自己手动存入到 HttpSession 中的数据,是不会被清除的
- sessionStatus.setComplete();
- }
-
- }
在springmvc中目前主流使用的是Jackson(重点)、gson、fastjson(了解)这三种方式,其中Jackson和gson只要引入依赖就可以使用,fastjson需要手动配置才能使用。
下面先介绍Jackson的使用方法:首先是导入Jackson的依赖,然后就可以使用了,如果需要个性定制时间显示格式,需要在xml配置文件中设置相应的bean
- <dependency>
- <groupId>com.fasterxml.jackson.core<