【问题标题】:How to get the model value from a method which has been included by previous method如何从先前方法包含的方法中获取模型值
【发布时间】:2015-06-29 11:12:53
【问题描述】:

我正在使用 Spring MVC

我有方法

@RequestMapping(value = "/firstMethod/getDetails", method = RequestMethod.GET)
@ResponseBody
public Map<String, Object> getFirstMethodDetails(HttpServletRequest request,
        HttpServletResponse response) {
 Map<String, Object> model = new HashMap<String, Object>();
 model.put("name", "Bryan");
 request.getRequestDispatcher("/secondmethod/getDetails")
                    .include(request, response);

 // want to access second methods model values here    

 return model;

}

我从中包含对另一个方法的请求

@RequestMapping(value = "/secondMethod/getDetails", method=RequestMethod.GET)
@ResponseBody
public Map<String, Object> getSecondMethodDetails(HttpServletRequest request,
        HttpServletResponse response) {
 Map<String, Object> model = new HashMap<String, Object>();
 model.put("age", 29);
 return model;
}

现在如何从第一种方法访问第二种方法的模型??

【问题讨论】:

    标签: spring-mvc servlets requestdispatcher


    【解决方案1】:

    要在重定向的两个控制器之间传递数据,您可以在 Flash 范围内使用自定义属性。

    在这里,您可以在 flash 范围内从第一个方法添加模型,并在第二个方法中访问它。

    http://java.dzone.com/articles/spring-mvc-flash-attributes

    @RequestMapping(method = RequestMethod.POST)
    
      public String handleFormSubmission(..., final RedirectAttributes     redirectAttrs) {
        ...
        redirectAttrs.addFlashAttribute("AttributeName", value);
        return "redirect:to_some_url_handled_by_BController";
    }
    

    发帖 - How to pass model attributes from one Spring MVC controller to another controller?

    【讨论】:

    • 我可以在转发时将数据从第一种方法传递到第二种方法,即使使用不成问题的查询参数也是如此。需求是如何获取第二种方法的模型属性,即转发的方法。从第一种方法
    • 将模型添加为自定义闪存范围属性是这种情况下推荐的方法。这样您也不需要为此添加自定义查询参数
    • 首先我不能使用重定向,因为我有一些代码需要在调用第二种方法后执行。使用重定向是不可能的,因为重定向字符串将是方法的最后一行。
    • 我不是 Spring 专家,但一个简单的请求属性不会在这里工作吗? IE。 request.setAttribute("secondModel", model); 在第二种方法中,Map&lt;String, Object&gt; modelFromSecondMethod = (Map&lt;String, Object&gt;) request.getAttribute("secondModel"); 在第一种方法中(在forward 调用之后)?
    • 还有一个原因是您不能在从控制器 1 调用的业务层类中的控制器 2(方法 2)中执行该过程吗?你绝对需要调用另一个控制器吗?
    猜你喜欢
    • 2021-11-27
    • 1970-01-01
    • 2019-01-07
    • 2015-11-06
    • 2012-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多