springMVC参数处理
一、ModelAndView作用
1、设置转向地址
2、将底层获取的数据进行存储(或者封装)
3、最后将数据传递给view
二、ModelAndView使用
方式一:ModelAndView第一种用法,先创建ModelAndView对象,再通过他的方法去设置与转发的视图名
@RequestMapping(value = "/test1", method = RequestMethod.GET)
public ModelAndView test1() {
ModelAndView modelAndView = new ModelAndView("home");
modelAndView.addObject("name", "test12222");
return modelAndView;
}
ModelAndView(String viewName):viewName name of the View to render, to be resolved by the DispatcherServlet’s ViewResolver
ModelAndView addObject(String attributeName, Object attributeValue):通过key/value的方式绑定数据
方式二:ModelAndView的第二种用法,可以直接通过带有构造方法ModelAndView(String viewName, String attributeName, Object attributeValue) 来返回数据与转发的视图名
public ModelAndView login(@RequestParam("name") String nametest, String pass) {
UserBean user = new UserBean();
user.setName(nametest);
user.setPass(pass);
Map<String, Object> data = new HashMap<String, Object>();
data.put("user", user);
return new ModelAndView("home", data);
}
方式三:ModelAndView自动注入对象
@RequestMapping("/loginbean")
public ModelAndView login(UserBean bean) {
Map<String, Object> data = new HashMap<String, Object>();
data.put("user", bean);
return new ModelAndView("home", data);
}
三、request
方式一:直接通过参数
public String test2(HttpServletRequest reques) {
reques.setAttribute("name_test2", "test2");
return "home";
}
方式二:全局注入
// request 方式
@RequestMapping("/test3")
public String test3() {
request.setAttribute("name_test3", "test3");
return "home";
}
四、参数动态处理
@RequestMapping("/url/{id}")
public String url1(UserBean bean, @PathVariable("id") Integer id) {
System.out.println(id);
request.setAttribute("user", bean);
request.setAttribute("id", id);
return "home";
}
ps:参考代码UserBean.java、HomeController.java
代码地址:https://github.com/HopeWing1286/SpringMvc.git