SSM-SpringMVC-深入SpringMVC组件-保存并获取属性参数

本文详细介绍了SpringMVC框架中如何使用@RequestAttribute、@SessionAttribute等注解来获取和设置HTTP请求及会话中的属性。同时,还探讨了如何通过@SessionAttributes注解配置特定的数据类型以保存到Session中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

SSM-SpringMVC-深入SpringMVC组件-保存并获取属性参数

​ 需要获取HTTP的request对象或者session对象中的数据,有时需要保存对应的数据到这些对象中或者获取,SpringMVC提供三个注解来支持这个功能:

  1. @RequestAttribute:获取Http的请求request对象属性值,用来专递给控制器的参数
  2. @SessionAttribute:在HTTP的会话Session对象属性值中,用来传递给控制器的参数
  3. @SessionAttributes:可以配置一个字符串数组,这个数组对应的数据类型对应的键值对,然后将键值对保存到Session中

@RequestAttribute

从HTTP的request对象中取出请求属性,如下:

@Controller
@RequestMapping("/attibute")
public class AttributeController{
    @Autowirer
    private RoleService roleService=null;
    
    @RequestMapping("/requestAttribute")
    public ModelAndView reqAttr(@RequestAttribute("id") Long id){
        ModelAndView mv=new ModelAndView();
        Role role=roleService.getRole(id);
        mv.addObject("role",role);
        mv.setView(new MappingJackson2JsonView());
        return mv;
    }  
}

通过前端转发到控制器reqAttr方法,参数中给予了@RequestAttribute注解,这样就能获取请求的id属性


@SessionAttribute和@SessionAttributes

  • @SessionAttributes:与HTTP会话对象有关,控制器通过它来设置对应键值对,该注解只能对类进行标注,可以配置属性名称或属性类型,SpringMVC执行完控制器逻辑后,将数据模型对应的属性名或者属性类型保存到HTTP的Session对象中

    @Controller
    @RequestMapping("/attibute")
    @SessionAttributes(name={"id"},types={Role.class})
    public class AttributeController{
        @Autowirer
        private RoleService roleService=null;
        
        @RequestMapping("/requestAttribute")
        public ModelAndView reqAttr(@RequestAttribute("id") Long id){
            ModelAndView mv=new ModelAndView();
            Role role=roleService.getRole(id);
            mv.addObject("role",role);
            mv.setView(new MappingJackson2JsonView());
            return mv;
        }  
    }
    
  • @SessionAttribute:作用获取Session属性

    @RequertMapping("/sessionAttribute")
    public ModelAndView sessionAttribute(@SessionAttribute("id") Long id){
            ModelAndView mv=new ModelAndView();
            Role role=roleService.getRole(id);
            mv.addObject("role",role);
            mv.setView(new MappingJackson2JsonView());
            return mv; 
    }
    

注解@CookieValue和注解@RequestHeader

​ 从Cookie和HTTP请求头中获取对应的请求信息

@RequertMapping("/getHeaderAndCookie")
public String testHeaderAndCookie(@RequestHeader(value="User-Agent",required=false,defaultValue="attribute") 
                                  String userAgent,
                                 @CookieValue(value="JSESSIONID",required=true,defaultValue="MyJsessionID")
                                 String jsessionId){
	System.out.println(userAgent);
    System.out.println(jsessionId);
    return "index";
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值