springMVC对session中数据的操作,也提供了自己的api。一般我们操作session的值都在控制器中,
往session存取值,主要依靠Model类的addAttribute(key,value)。如果是请求转发的话,可以不必再控制器中添加@SessionAttributes的注解,names为字符串数组,数组中的元素,即对应model的addAttribute中的key。如果是重定向的,则需要添加@SessionAttributes的注解,否则是取不到值的。
。也可以是用Servlet-api的HttpSession也行。
@Controller
@RequestMapping("/demo")
@SessionAttributes(names={"username"})
public class DemoController {
@Autowired
private DemoService demoService;
@RequestMapping("/mapper")
public String demoMapper(){
System.out.println(" i come on");
demoService.service();
return "redirect:/index.jsp";
}
@RequestMapping(value="/register",method=RequestMethod.POST)
public String register(Student s){
System.out.println(s);
//demoService.service();
return "redirect:/index.jsp";
}
@RequestMapping(value="/register",method=RequestMethod.POST)
public String register(Student s,HttpSession session){
System.out.println(s);
session.setAttribute("username", s.getName());
//demoService.service();
return "redirect:/index.jsp";
}
@RequestMapping(value="/login/{username}")
public String login(@PathVariable("username") String username,Model model){
System.out.println(username);
model.addAttribute("username", username);
//demoService.service();
return "redirect:/index.jsp";
}
}