多语言展示
当前在线:537今日阅读:60今日分享:41

SpringMVC如何设置、获取及清除Session

本文主要通过举例介绍SpringMVC如何实现设置、获取及清除Session的功能。
工具/原料

SpringMVC

方法/步骤
1

在Controller上加上注解@SessionAttributes(value = {'student1','student2'}),表明将student1和student2对象保存到session中

2

setSession函数实现了向Session中添加student1和student2的功能

3

以下两个函数clearSession、getSession分别实现了清除session和获取session中的student1及student2的功能

4

输入url映射/testSession/setSession进入setSession方法设置student1,student2,并将其置入session中

5

输入url映射/testSession/getSession进入getSession方法获取session中的属性student1,student2

6

分别输入url映射/testSession/clearSession,/testSession/getSession清空session和获取session

7

完成测试代码如下:@Controller@RequestMapping(value = '/testSession')@SessionAttributes(value = {'student1','student2'})public class SessionController{    @RequestMapping('setSession')    public void setSession(Model model, HttpSession session)    {        Student student1 = new Student();        student1.setName('lisa');        student1.setAge(18);        student1.setCountry('America');        Student student2 = new Student();        student2.setName('yc');        student2.setAge(20);        student2.setCountry('China');        model.addAttribute('student1',student1);        model.addAttribute('student2',student2);        System.out.println('set session ok.');    }    @RequestMapping('clearSession')    public void clearSession(SessionStatus sessionStatus, HttpSession session){        sessionStatus.setComplete();        System.out.println('clear session ok.');    }    @RequestMapping(value = 'getSession')    public void getSession(HttpSession session)    {        System.out.println('get session: student1 = '  + session.getAttribute('student1'));        System.out.println('get session: student2 = '  + session.getAttribute('student2'));    }}

注意事项

如果小编所写经验帮助到了你,请帮忙给点个赞或评论支持下,您的支持是作者继续创作的动力!

推荐信息