Issue
I'm new in Spring, and I'm trying to better undestand the MVC framework. Considering the following 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>
I see that, in a @Controller class:
@GetMapping("/EntryPoint1")
public String helloView1(Model model) {
model.addAttribute("username", "pippo");
return "HelloWorld";
}
it uses as username
value the one inserted in model
.
However, if I declare both the Model model
parameter and I return a ModelAndView
object, that is:
@GetMapping("/EntryPoint2")
public ModelAndView helloView2(Model model) {
model.addAttribute("username", "pluto");
ModelAndView mav = new ModelAndView("HelloWorld");
mav.addObject("username", "paperino");
return mav;
}
I obtain that the value used by the view is the one contained in mav
ignoring the value in model
. Is there an explanation for this (for example, any kind of precedence between the objects considered by the view)?
Solution
see, here in model.addAttribute("username", "pluto"); and in mav.addObject("username", "paperino"); username is same so priorities goes to ModelAndView, However u change the name then u can render them both and access.
Answered By - manish