从Spring MVC控制器注入JSP [英] Injecting JSP from Spring MVC controller

查看:82
本文介绍了从Spring MVC控制器注入JSP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a Spring MVC web app that uses JSP for the View technology. In the controller I am injecting values into the ModelAndView object that will then be used (with the respective JSP) to help construct the final HTML to return to the client-side.

控制器:

@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中将它们打印出来:

This controller (which handles /widgets.html requests) does some lookups and returns the injected AllWidgets.jsp page. In that JSP page, I need to get access to both the fruitType and buzz variables (inside both HTML and JS), but not sure how I can do this. For instance, assuming fruitType is a String (and buzz is an int), how would I print them in both HTML and JS:

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

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

谢谢.

推荐答案

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

The Spring controller stores the view objects in the page context, and they are accessed using EL:

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

这在Oracle Java EE教程中进行了描述,以及 Spring MVC教程中.

This is described in the Oracle Java EE Tutorial, and also in the introductory Spring MVC tutorial.

这篇关于从Spring MVC控制器注入JSP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆