什么是最优雅/最有效的方式,如何在 Spring MVC 3.2 中处理 Controller 之间的模型。为了重定向到另一个 Controller ,我使用 forward 方法,因此不需要新的请求实例,模型数据应该可以访问(如果我没记错的话)。有什么方法可以捕获在第一个 Controller 中添加的模型吗?
(我知道 RedirectAttributes,但可能是更好/更简单的方法)
例子:
@Controller
public class WebpageController{
@RequestMapping( value = { "/{code}" } )
public String handleFirstLevel(@PathVariable String code, ModelMap modelMap) throws PageNotFoundEception{
final Webpage webpage = getWebpage(code);
modelMap.put(WEBPAGE_MODEL_KEY, prepareModel(webpage));
return "forward:some-url";
}
private Map<String, Object> prepareModel(Webpage webpage){
Map<String, Object> model = new HashMap<String, Object>();
model.put("webpage", webpage);
return model;
}
// some other code
}
@Controller
public class SpecialWebpageController{
@RequestMapping( value = { "/some-url" } )
public String handleFirstLevel(@PathVariable String code, ModelMap modelMap) throws PageNotFoundEception{
// need access to previously appended model to add some other data
return "specialViewName";
}
}
谢谢
最佳答案
当您有一个仅返回 String
的处理程序方法时,该 String
被视为 View 名称。使用 forward
前缀,Spring 将获取指定路径的 RequestDispatcher
并转发给它。该过程的一部分将包括从为该请求处理周期创建的 ModelAndView
中获取 Model
,并将其所有属性放入 HttpServletRequest
属性中。
Servlet 容器将采用 RequestDispatcher#forward(..)
并再次使用您的 DispatcherServlet
来处理它。您的 DispatcherServlet
将为此处理周期创建一个带有新 Model
的新 ModelAndView
。因此,此 Model
不包含之前的任何属性,但 HttpServletRequest
属性包含。
在你的情况下,这个
modelMap.put(WEBPAGE_MODEL_KEY, prepareModel(webpage));
最终会在
HttpServletRequest request = ...;
request.getAttribute(WEBPAGE_MODEL_KEY);
关于java - 如何在 Spring MVC 中使用转发处理 Controller 之间的 ModelMap 的有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22972762/