2012-09-20 44 views
2

我认为最初的问题很混乱。Spring MVC和请求属性

我有一个HashMap,需要从我想通过Spring Controller发送到视图的数据库收集。我不想把这个HashMap放在model.addAttribute()中,因为Spring Model对象返回一个Map,而我的JSP需要的集合是Collection<Object>。如果我将我的HashMap.values()设置为request.setAttribute,如果我的方法返回一个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"; 
} 

编辑:春天标签库不能用于这个特殊的用例。

谢谢。

+0

您使用Spring MVC并且不能使用Spring Taglibs,它是** Spring MVC jar中的** - 为什么不呢? – Xaerxess

+0

我可以使用它,但我使用的TagLib适合我们正在使用的系统的界面。用户期望它看起来有某种特定的方式。 – Robert

+0

因此,如果您使用addAttribute将其添加到模型中,那么您是不是可以使用home.jsp中的$ {surveys}简单地访问它? – digitaljoel

回答

4

如果mySurveys是一个地图,那么也许你可以把mySurveys.values()到ModelMap代替mySurveys(也,你打算使用一个ModelMap,而不是一个型号的?)

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

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

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

谢谢@Matt。我在发布前一个小时就意识到了这一点,是的,我需要Model而不是ModelMap。接得好。 – Robert

1

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

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

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

希望这回答你的问题

+0

我不能使用Spring标签,但我正在使用另一个拥有自己的api和taglib的框架。我将不得不使用$ {variable}语法来显示它。 – Robert

+0

你可以发布我们正在谈论的代码部分吗? – th3an0maly

+0

我发布了我正在尝试做的事 – Robert