【问题标题】:Spring MVC and Request AttributesSpring MVC 和请求属性
【发布时间】:2012-09-13 05:05:15
【问题描述】:

我认为最初的问题令人困惑。

我有一个 HashMap,它需要是来自数据库的集合,我想通过 Spring 控制器发送到视图。我不想将这个 HashMap 放在 model.addAttribute() 中,因为 Spring Model 对象返回一个 Map,而我的 JSP 需要集合是 Collection<Object>。如果我在 request.setAttribute 中设置我的 HashMap.values(),如果我的方法返回一个字符串,我该如何将该请求变量分派到视图?

@RequestMapping(method = RequestMethod.GET)
public String home(Locale locale, Model model, HttpServletRequest request) {

    model.addAttribute("surveys", mySurveys); //this is a map and I need a Collection<Object>

    //So I'd like to do this, but how do I get to the "evaluations" object in a view if I'm not dispatching it (like below)??
    request.setAttribute("evaluations", mySurveys);

    //RequestDispatcher rd = request.getRequestDispatcher("pathToResource");
    //rd.forward(request, response);

    return "home";
}

编辑:Spring Tag 库不能用于此特定用例。

谢谢。

【问题讨论】:

  • 你使用 Spring MVC 并且不能使用 Spring Taglibs,这是 in Spring MVC jar - 为什么不呢?
  • 我可以使用它,但是我使用的 TagLib 适合我们正在使用的系统的接口。用户希望它看起来像某种方式。
  • 所以如果你使用 addAttribute 将它添加到模型中,你不能简单地使用 home.jsp 中的 ${surveys} 访问它吗?
  • 我得到一个异常,因为标签(构建数据表)需要一个 Collection 对象而不是地图。
  • 你能展示声明和实例化 mSurveys 的代码吗?

标签: java jsp servlets spring-mvc controller


【解决方案1】:

如果 mySurveys 是 Map,那么也许您可以将 mySurveys.values() 放入 ModelMap 而不是 mySurveys(另外,您是否打算使用 ModelMap 而不是 Model?)

在下面的代码中,调查将是对象的集合,并且可以通过 ${surveys} 在 jsp 中访问

@RequestMapping(method = RequestMethod.GET)
public String home(ModelMap modelMap, HttpServletRequest request) {

    Map<String,Object> mySurveys = getMySurveys();
    modelMap.addAttribute("surveys", mySurveys.values());
    return "home";
}

【讨论】:

  • 谢谢@Matt。我在您发布之前大约一个小时就意识到了这一点,是的,我需要 Model 而不是 ModelMap。很好的收获。
【解决方案2】:

我认为您对 ModelMap 是什么感到困惑。

您可以通过@ModelAttribute 在视图中注释您想要访问的任何变量,Spring 会自动实例化它,并将其添加到ModelMap。在视图中,您可以像这样使用它:

<form:form modelattribute="myAttribute">
    <form:input path="fieldInAttribute">
</form:form>

希望这能回答你的问题

【讨论】:

  • 我将无法使用 Spring 标签,但我正在使用另一个拥有自己的 api 和 taglib 的框架。我必须使用 ${variable} 语法来显示它。
  • 我发布了我正在尝试做的事情
猜你喜欢
  • 2019-08-05
  • 2014-02-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-15
  • 2011-12-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多