如何在Spring MVC 3.1中重定向后读取flash属性?

Rub*_*zzo 38 java spring-mvc

我想知道如何在Spring MVC 3.1中重定向后读取flash属性.

我有以下代码:

@Controller
@RequestMapping("/foo")
public class FooController {

  @RequestMapping(value = "/bar", method = RequestMethod.GET)
  public ModelAndView handleGet(...) {
    // I want to see my flash attributes here!
  }

  @RequestMapping(value = "/bar", method = RequestMethod.POST)
  public ModelAndView handlePost(RedirectAttributes redirectAttrs) {
    redirectAttrs.addFlashAttributes("some", "thing");
    return new ModelAndView().setViewName("redirect:/foo/bar");
  }

}
Run Code Online (Sandbox Code Playgroud)

我错过了什么?

Xae*_*ess 51

使用时Model,应预先填充闪存属性:

@RequestMapping(value = "/bar", method = RequestMethod.GET)
public ModelAndView handleGet(Model model) {
  String some = (String) model.asMap().get("some");
  // do the job
}
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用RequestContextUtils#getInputFlashMap:

@RequestMapping(value = "/bar", method = RequestMethod.GET)
public ModelAndView handleGet(HttpServletRequest request) {
  Map<String, ?> inputFlashMap = RequestContextUtils.getInputFlashMap(request);
  if (inputFlashMap != null) {
    String some = (String) inputFlashMap.get("some");
    // do the job
  }
}
Run Code Online (Sandbox Code Playgroud)

PS你可以做回return new ModelAndView("redirect:/foo/bar");handlePost.

编辑:

JavaDoc说:

调用方法时,RedirectAttributes模型为空,除非方法返回重定向视图名称或RedirectView,否则永远不会使用.

它没有提ModelAndView,所以可能更改handlePost返回"redirect:/foo/bar"字符串或RedirectView:

@RequestMapping(value = "/bar", method = RequestMethod.POST)
public RedirectView handlePost(RedirectAttributes redirectAttrs) {
  redirectAttrs.addFlashAttributes("some", "thing");
  return new RedirectView("/foo/bar", true);
}
Run Code Online (Sandbox Code Playgroud)

我用RedirectAttributes我的代码RedirectViewmodel.asMap()方法,它工作正常.

  • 谢谢,它通过返回一个`RedirectView`就像一个魅力. (5认同)

Jaf*_*dog 30

试试这个:

@Controller
public class FooController
{
    @RequestMapping(value = "/foo")
    public String handleFoo(RedirectAttributes redirectAttrs)
    {
        redirectAttrs.addFlashAttribute("some", "thing");
        return "redirect:/bar";
    }

    @RequestMapping(value = "/bar")
    public void handleBar(@ModelAttribute("some") String some)
    {
        System.out.println("some=" + some);
    }
}
Run Code Online (Sandbox Code Playgroud)

适用于Spring MVC 3.2.2

  • 请注意,您无法检查自定义对象上的“属性是否已填充”。即使重定向属性中没有给定名称的对象,`@ModelAttribute` 也返回非空。 (2认同)