将bean的属性重定向为参数

时间:2016-04-22 17:15:31

标签: java spring spring-mvc

我的控制器像bellow一样期望ModelAttribute类型为Foo

@RequestMapping(value="/search") 
public String search(ModelMap model, @ModelAttribute Foo foo,
          HttpServletRequest request) {

        .....
}   

在另一个控制器中,我想将我的bean Foo重定向为我的请求的参数/search

@RequestMapping(value="/load_search") 
public String load_search(ModelMap model, @ModelAttribute Foo foo, 
            HttpServletRequest request) {

    Foo foo = myService.getFoo();
    return "redirect:/search";
}

那我怎么能实现呢?如何使用我的bean foo作为参数重定向到/search/search?arg0=..&arg1=..其中arg0, arg1 , ...是bean Foo的属性?

1 个答案:

答案 0 :(得分:2)

您可以使用RedirectAttributes。它是特殊参数,允许您传递数据抛出重定向。让我们考虑一下您的代码段示例:

@RequestMapping(value="/load_search") 
public String load_search(ModelMap model, @ModelAttribute Foo foo, 
            HttpServletRequest request, RedirectAttributes redirectAttrs) {

    Foo foo = myService.getFoo();
    redirectAttrs.addFlashAttribute("foo", foo);
    return "redirect:/search";
}

目标方法foo将由Spring自动添加到模型中。如果您需要将foo映射到@ModelAttribute参数,则应明确指定属性名称,如以下示例所示:

@RequestMapping(value="/search") 
public String search(ModelMap model, @ModelAttribute("foo") Foo foo,
          HttpServletRequest request) {

     //here 'foo' will be added to 'model' and mapped to 'foo'
     .....
}   

有关RedirectAttributes的详细信息,请参阅Spring documentation