SPRING MVC:返回 ModelAndView/parameters 优先级
SPRING MVC: returned ModelAndView/parameters precedence
我是 Spring 的新手,我正在努力更好地理解 MVC 框架。
考虑以下 jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Hello World!</title>
</head>
<body>
Welcome <%=request.getAttribute("username")%>
</body>
</html>
我看到了,在@Controller class:
@GetMapping("/EntryPoint1")
public String helloView1(Model model) {
model.addAttribute("username", "pippo");
return "HelloWorld";
}
它使用 username
值插入 model
。
但是,如果我同时声明 Model model
参数和 return 一个 ModelAndView
对象,即:
@GetMapping("/EntryPoint2")
public ModelAndView helloView2(Model model) {
model.addAttribute("username", "pluto");
ModelAndView mav = new ModelAndView("HelloWorld");
mav.addObject("username", "paperino");
return mav;
}
我得到视图使用的值是 mav
中包含的值,忽略了 model
中的值。对此是否有解释(例如,视图考虑的对象之间的任何优先级)?
看这里 model.addAttribute("username", "pluto");
在 mav.addObject("用户名", "paperino");
用户名相同,所以优先级转到 ModelAndView,但是你更改名称然后你可以同时呈现它们并访问。
我是 Spring 的新手,我正在努力更好地理解 MVC 框架。 考虑以下 jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Hello World!</title>
</head>
<body>
Welcome <%=request.getAttribute("username")%>
</body>
</html>
我看到了,在@Controller class:
@GetMapping("/EntryPoint1")
public String helloView1(Model model) {
model.addAttribute("username", "pippo");
return "HelloWorld";
}
它使用 username
值插入 model
。
但是,如果我同时声明 Model model
参数和 return 一个 ModelAndView
对象,即:
@GetMapping("/EntryPoint2")
public ModelAndView helloView2(Model model) {
model.addAttribute("username", "pluto");
ModelAndView mav = new ModelAndView("HelloWorld");
mav.addObject("username", "paperino");
return mav;
}
我得到视图使用的值是 mav
中包含的值,忽略了 model
中的值。对此是否有解释(例如,视图考虑的对象之间的任何优先级)?
看这里 model.addAttribute("username", "pluto"); 在 mav.addObject("用户名", "paperino"); 用户名相同,所以优先级转到 ModelAndView,但是你更改名称然后你可以同时呈现它们并访问。