Spring MVC和Request Attributes

时间:2012-09-20 19:09:12

标签: java jsp servlets spring-mvc controller

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

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

@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库不能用于此特定用例。

感谢。

2 个答案:

答案 0 :(得分:4)

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

在下面的代码中,调查将是一个对象集合,可以通过$ {survey}

在jsp中访问
@RequestMapping(method = RequestMethod.GET)
public String home(ModelMap modelMap, HttpServletRequest request) {

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

答案 1 :(得分:1)

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

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

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

希望这能回答你的问题