天天看点

使用SpringMVC的注解@SessionAttribute(value="keyname")操作HttpSession对象

1、Servlet中,HttpSession的使用;HttpSession session=request.getSession;session.setAttribute("keyname",keyvalue);

2、SpringMVC中@SessionAttributes(value="keyname")(单个key)/@SessionAttributes({"keyname1","keyname2"})(多个key)来操作HttpSession.(1)在类的上方使用注解@SessionAttributes(value="keyname").这个表示如果Model存在keyname的key,就把key及其对应的值存在HttpSession中,相当于session.setSession("keyname",keyvalue);(2)创建一个带有@RequestMapping 的putSession(Model model)方法,使用model.setAttribute("keyname",keyvalue);来和1对应(3)在jsp文件中,使用EL表达式${requestScope.keyname}、${sessionScope.keyname}均可以获得HttpSession所存取的值

3、代码:

package controller;

import org.springframework.stereotype.Controller;

import org.springframework.ui.Model;

import org.springframework.web.bind.annotation.ModelAttribute;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.SessionAttributes;

@Controller

@SessionAttributes(value="username")

public class DoHttpSessionByAnnotation {

@RequestMapping(value="putSession")

 public String putSession(Model model){

model.addAttribute("username","cgq");

return "index.jsp";

 }

@RequestMapping(value="getSession")

public String getSession(Model model,@ModelAttribute("username") String username ){

System.out.println(username);

return "pp.jsp";

}

}