Spring MVC系列(四)之session处理---@SessionAttributes

介绍

       在web开发中,session的重要性不言而喻,与cookie相比,session更加安全,处于服务器端,开发者经常把一些重要的信息放在session,方便在多次请求中方便的获取信息,Spring MVC 对session的支持也依旧很强大很灵活


Spring MVC对session的支持分为两种

基于HttpSession的天然支持

基于注解@SessionAttributes的灵活多变的支持


首先我们先一起分析一下基于天生的HttpSession的支持吧

加入用户登录的时候,我们把用户信息记录到session中

package org.study.lyncc.web.controller;

import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.study.lyncc.web.entity.User;

@Controller
public class SessionAttributesController {
    
    /**
     * user对象存入session
     * @param id
     * @param name
     * @param session
     * @return
     */
    @RequestMapping("/session/test/{id}/{name}")
    public ModelAndView localsessionAttributes(@PathVariable Integer id,@PathVariable String name,HttpSession session){
        session.setAttribute("currentUser", new User(id,name));
        ModelAndView mav = new ModelAndView("session");
        return mav;
    }
    
    /**
     * 获取session中的user对象
     * @param session
     * @return
     */
    @RequestMapping("/session/attributes")
    public ModelAndView sessionAttributesage(HttpSession session){
        User u = (User)session.getAttribute("currentUser");
        System.out.println(u.getUsername());
        ModelAndView mav = new ModelAndView("session");
        return mav;
    }
    
}
我们先请求http://localhost:8080/spring-mvc/session/test/1/lyncc

然后我们再次请求http://localhost:8080/spring-mvc/session/attributes

会发现我们可以冲session取出我们上次请求存入session的user对象,并成功打印user的名字


基于@SessionAttributes注解实现的对session的管理

SessionAttributes是只能注解于类或者接口,@SessionAttributes的value代表我们需要把什么样的对象放入session,在我们的方法后当我们把对象放入ModelMap这个对象的时候,如果给出的key也会自动放入session的,我们举例说明

package org.study.lyncc.web.controller;

import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;
import org.study.lyncc.web.entity.User;

@Controller
@SessionAttributes(value="currentUser")
public class SessionAttributesController {
    
    
    
    @RequestMapping("/session/attributes/{id}/{name}")
    public ModelAndView sessionAttributes(@PathVariable Integer id,@PathVariable String name){
        ModelAndView mav = new ModelAndView("session");
        mav.addObject("currentUser", new User(id,name));
        return mav;
    }
    
    /**
     * 获取session中的user对象
     * @param session
     * @return
     */
    @RequestMapping("/session/attributes")
    public ModelAndView sessionAttributesage(HttpSession session){
        User u = (User)session.getAttribute("currentUser");
        System.out.println(u.getUsername());
        ModelAndView mav = new ModelAndView("session");
        return mav;
    }
    
}

上面代码中,我们注解了@SessionAttributes,并且在sessionAttributes方法中,mav.addObject("currentUser", new User(id,name));我们创建一个对象放入ModelAndView中,因为@SessionAttributes的value与addObject的key值相同,所以该User会自动存入session中(上面说是ModelMap对象,其实看源码就知道ModelAndView的model就是ModelMap)

好了,我们测试一下,先运行http://localhost:8080/spring-mvc/session/test/1/lyncc

再运行http://localhost:8080/spring-mvc/session/attributes,测试结果


能获取到值,说明user放入session成功了



我们除了显性的从HttpSession中获取对象,我们还可以利用@ModelAttribute与@SessionAttributes相互配合,隐性的获取到放在session中的值,代码如下

package org.study.lyncc.web.controller;

import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;
import org.study.lyncc.web.entity.User;

@Controller
@SessionAttributes(value="currentUser")
public class SessionAttributesController {
    
    
    
    @RequestMapping("/session/attributes/{id}/{name}")
    public ModelAndView sessionAttributes(@PathVariable Integer id,@PathVariable String name){
        ModelAndView mav = new ModelAndView("session");
        mav.addObject("currentUser", new User(id,name));
        return mav;
    }
    
    
    @RequestMapping("/session/attributes/test")
    public ModelAndView sessionAttributesage(@ModelAttribute("currentUser") User u){
        System.out.println(u.getUsername());
        ModelAndView mav = new ModelAndView("session");
        return mav;
    }


}
这样依旧能获取到值,不过要注意



最后我们再看看@SessionAttributes这个注解



package org.springframework.web.bind.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import org.springframework.core.annotation.AliasFor;


@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface SessionAttributes {

	
	@AliasFor("names")
	String[] value() default {};

	
	@AliasFor("value")
	String[] names() default {};

	
	Class<?>[] types() default {};

}
都是数组型的,也就说可以支持多个对象放入session中,举例说明

package org.study.lyncc.web.controller;

import java.util.Date;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;
import org.study.lyncc.web.entity.User;

@Controller
@SessionAttributes(value={"currentUser","saveTime"},types={User.class,Date.class})
public class SessionAttributesController {
    
    @RequestMapping("/session/attributes/{id}/{name}")
    public ModelAndView sessionAttributes(@PathVariable Integer id,@PathVariable String name){
        ModelAndView mav = new ModelAndView("session");
        mav.addObject("currentUser", new User(id,name));
        mav.addObject("saveTime", new Date());
        return mav;
    }
    
    
    @RequestMapping("/session/attributes/test")
    public ModelAndView sessionAttributesage(@ModelAttribute("currentUser") User u,@ModelAttribute("saveTime") Date d){
        System.out.println(u.getUsername());
        System.out.println(d);
        ModelAndView mav = new ModelAndView("session");
        return mav;
    }
}
测试结果:


好了,这节END~









  • 3
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值