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

2025-11-07 06:51:32

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

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

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

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

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

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

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

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

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

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

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

SpringMVC如何设置、获取及清除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"));

    }

}

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

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢