【问题标题】:Injecting JSP from Spring MVC controller从 Spring MVC 控制器注入 JSP
【发布时间】:2012-12-08 05:04:29
【问题描述】:

我有一个使用 JSP 作为 View 技术的 Spring MVC Web 应用程序。在控制器中,我将值注入到 ModelAndView 对象中,然后将使用该对象(与相应的 JSP 一起)帮助构造最终的 HTML 以返回到客户端。

控制器:

@RequestMapping(value = "/widgets.html", method = RequestMethod.POST)
public ModelAndView widgets(@Model Fruit fruit, @RequestParam("texture") String texture) {
    ModelAndView mav = new ModelAndView();

    // The name of the JSP to inject and return.
    max.setViewName("widgets/AllWidgets");

    int buzz = calculateBuzzByTexture(texture);

    mav.addObject("fruitType", fruit.getType());
    mav.addObject("buzz", buzz);

    return mav;
}

此控制器(处理/widgets.html 请求)进行一些查找并返回注入的AllWidgets.jsp 页面。在那个 JSP 页面中,我需要同时访问 fruitTypebuzz 变量(在 HTML 和 JS 中),但我不确定我该怎么做。例如,假设fruitType 是一个字符串(而buzz 是一个int),我将如何在HTML 和JS 中打印它们:

<script type="text/javascript>
    alert("Buzz is " + buzz);
</script>

<div>
    <h2>The type of fruit is ??? fruitType ???</h2>
</div>

提前致谢。

【问题讨论】:

    标签: java javascript jsp spring-mvc


    【解决方案1】:

    Spring 控制器将视图对象存储在页面上下文中,并使用 EL 访问它们:

    <div>
        <h2>The type of fruit is ${fruitType}</h2>
    </div>
    

    这在 Oracle Java EE Tutorial 和介绍性 Spring MVC tutorial 中有描述。

    【讨论】:

    • 感谢@parsifal (+1) - 我 假设 在 Javascript 中也是如此?再次感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-11-06
    • 2020-10-13
    • 2012-11-04
    • 1970-01-01
    • 2012-12-08
    • 1970-01-01
    • 2013-05-31
    相关资源
    最近更新 更多