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

一、@SessionAttributes注解

        如果在类上加有@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<String> 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中的Json

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

Jackson:

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

        <dependency>
            <groupId>com.fasterxml.jackson.core&
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

白昼乌龙茶

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值