关于java:Spring MVC和请求属性

Spring MVC and Request Attributes

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

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

1
2
3
4
5
6
7
8
9
10
11
12
13
@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库不能用于此特定用例。

谢谢。


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

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

在jsp中进行访问。

1
2
3
4
5
6
7
@RequestMapping(method = RequestMethod.GET)
public String home(ModelMap modelMap, HttpServletRequest request) {

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


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

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

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

希望这能回答您的问题