Spring MVC一些常见注解的使用(二)
关于Session的一些注解
@SessionAttributes
这个注解就可以解决,Session的存取的时候更加有可读性。最关键的是,@SessionAttributes和Model/ModelMap/Map在Controller方法里面的使用。
在没有使用 @SessionAttributes注解的时候,Map/Model/ModelMap
@RequestMapping(value="login")
public String login(Map model) throws IOException{
model.put("age", 18);
return "index";
}
@RequestMapping(value="isLogin")
@ResponseBody
public String isLogin(Map model){
System.out.println(model.get("age"));
return "sucess";
}
此时打印的Map里面的值没有任何值。如何使Map/Model/ModelMap存放的值可以跨方法。也就是存放在Session中,常规的Session写法在存入对象比较复杂的时候略微有点转型的麻烦。
常规的获取Session写法,其实就必须告诉其他编写的人,只看方法是不知道里面有什么值的。
@RequestMapping(value="login")
public String login(HttpSession session) throws IOException{
session.setAttribute("1", "1");
return "index";
}
@RequestMapping(value="isLogin")
@ResponseBody
public String isLogin(HttpSession HttpSession session){
System.out.println(session.Attribute("1"));
return "sucess";
}
使用Map的时候,可以放入更加复杂的对象,看方法的时候就可以知道怎么获取内容
@Controller
@RequestMapping(value="/user")
@SessionAttributes(value={"age"})
public class UserController {
@RequestMapping(value="login")
public String login(Map<String,Integer> model) throws IOException{
model.put("age", 18);
return "index";
}
@RequestMapping(value="isLogin")
@ResponseBody
public String isLogin(Map<String,Integer> model){
System.out.println(model.get("age"));
return "sucess";
}
}
Map的使用和Model/ModelMap的用法基本一致。如果没有存入很复杂的对象,建议直接HttpSession,很复杂的话使用Map的可读性要变得好很多。
@SessionAttributes注解的一些属性
Optional Elements
Modifier and Type | Optional Element and Description |
---|---|
String[] | names The names of session attributes in the model that should be stored in the session or some conversational storage. |
Class<?>[] | types The types of session attributes in the model that should be stored in the session or some conversational storage. |
String[] | value Alias for |
@ModelAttribute
@ModelAttribute 主要有两种使用方式,一种是标注在方法上,一种是标注在 Controller 方法参数上。
当 @ModelAttribute 标记在方法上的时候,该方法将在处理器方法执行之前执行,然后把返回的对象存放在 session 或模型属性中,属性名称可以用 @ModelAttribute(“attributeName”) 在标记方法的时候指定,若未指定,则使用返回类型的类名称(首字母小写)作为属性名称。关于 @ModelAttribute 标记在方法上时对应的属性是存放在 session 中还是存放在模型中
当 @ModelAttribute 标记在处理器方法参数上的时候,表示该参数的值将从模型或者 Session 中取对应名称的属性值,该名称可以通过 @ModelAttribute(“attributeName”) 来指定,若未指定,则使用参数类型的类名称(首字母小写)作为属性名称
@ModelAttribute("name")
public String name(){
return "cdk";
}
@RequestMapping(value="model")
public String model(@ModelAttribute("name") String name){
System.out.println(name);
return "index";
}
对于一些想默认放入Session中的内容就使用这个。他会提前放入。
参考博客:http://haohaoxuexi.iteye.com/blog/1753271