【问题标题】:SPRING MVC: returned ModelAndView/parameters precedenceSPRING MVC:返回 ModelAndView/参数优先级
【发布时间】:2021-08-20 12:21:09
【问题描述】:

我是 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 类中:

@GetMapping("/EntryPoint1")
public String helloView1(Model model) {
    model.addAttribute("username", "pippo");
    return "HelloWorld";

}

它使用插入model 的值作为username 值。

但是,如果我同时声明 Model model 参数并返回一个 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 中的值。对此是否有解释(例如,视图所考虑的对象之间的任何优先级)?

【问题讨论】:

    标签: java spring spring-mvc model-view-controller


    【解决方案1】:

    看,这里是 model.addAttribute("username", "pluto"); 并在 mav.addObject("username", "paperino"); 用户名相同,因此优先级转到 ModelAndView,但是您更改名称然后您可以同时呈现它们并访问。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多