目录
ModelAttribute用法
一:标注在方法上
controller中的每个方法访问时都会首先执行标有ModelAttribute注解的方法,并把方法返回值放入request域中
二:标注在方法的参数上
用来通过名称对应,把相应名称的值绑定到注解的参数bean上
要绑定的值来源于:
A) @SessionAttributes 启用的attribute 对象上;
B) @ModelAttribute 用于方法上时指定的model对象;
C) 上述两种情况都没有时,new一个需要绑定的bean对象,然后把request中按名称对应的方式把值绑定到bean中。
测试代码:
重定向传参RedirectAttributes
一 : 拼接到url上
- 放入了request域中,会自动拼接到url上,地址栏 可以看到
redirectAttributes.addAttribute("param1", "msg1");
- 也可以自己直接拼入地址栏
return "redirect:/hello/getUiModel?param2=msg2";
二 : 放入session中
- 放入了session中,地址栏看不到
redirectAttributes.addFlashAttribute("user", user);
也可以自己放入session中
@Controller
@RequestMapping("/hello")
public class HelloController {
@ModelAttribute
public User sendRedirect() {
User user = new User();
user.setAge("23");
user.setUserName("ljj");
return user;
}
@RequestMapping("/sendRedirect")
public String sendRedirect(RedirectAttributes model, HttpServletResponse response) throws ServletException, IOException {
model.addAttribute("param1", "msg1");//放入了request域中,会自动拼接到url上,地址栏可以看
model.addFlashAttribute("user", user);//放入了session中,地址栏看不到
return "redirect:/hello/getUiModel?param2=msg2";//也可以自己直接拼入地址栏
}
//返回界面
@RequestMapping("/getUiModel")
public String getUiModel(HttpServletRequest request, @ModelAttribute("user") User user, String param1, String param2) {
System.out.println("param1=" + param1);
System.out.println("param2=" + param2);
System.out.println("userName" + user.getUserName());
request.setAttribute("user", "师姐");
return "forward:/welcome.jsp";
}
}