Spring-MVC 里面的ModelAndView

作用:

由于本身http是无状态的并不会保存什么请求信息。  但是目标页面可能又需要一些信息。这时候可以用ModelAndView存放一些业务数据之类等。然后返回给页面

 

用法:

比较重要的方法:

往对象里面加入变量

    /**
     * Add an attribute to the model.
     * @param attributeName name of the object to add to the model (never {@code null})
     * @param attributeValue object to add to the model (can be {@code null})
     * @see ModelMap#addAttribute(String, Object)
     * @see #getModelMap()
     */
    public ModelAndView addObject(String attributeName, @Nullable Object attributeValue) {
        getModelMap().addAttribute(attributeName, attributeValue);
        return this;
    }

 

设置需要放回的页面

    /**
     * Set a view name for this ModelAndView, to be resolved by the
     * DispatcherServlet via a ViewResolver. Will override any
     * pre-existing view name or View.
     */
    public void setViewName(@Nullable String viewName) {
        this.view = viewName;
    }

 

使用:

 @RequestMapping("/findAll")
    public ModelAndView accFindAll(){
        ModelAndView mv = new ModelAndView();
        System.out.println("springmvcdone1");
        Account account = accountService.findAll();
        mv.addObject("at",account);
        mv.addObject("atmoney",account.getMoney());
        mv.setViewName("list");
        System.out.println("springmvcdone2");
        return mv;
    }

 

jsp:

<html>
<head>
    <title>findAll</title>
</head>
<body>
${requestScope.atmoney}
${requestScope.at.toString()}
${requestScope.get("atmoney")}
</body>
</html>

 

如果上面的jsp没有获取到变量的值

可能的原因

${resquestScope.get(“param_name”)}
${resquestScope.atmoney} 访问结果是字符串,没有访问到变量
在于老的JSP 1.2 声明.
JSP 1.2
EL是默认关闭的必须手动打开。<%@ page isELIgnored="false" %>
但如果是JSP2.0版就可以直接用。
只需要在编译的JSP文件中头文件中加入:<%@ page isELIgnored="false" %>

 

posted @ 2020-08-02 22:48  小丑quan  阅读(205)  评论(0编辑  收藏  举报