Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
220 views
in Technique[技术] by (71.8m points)

java - How to read flash attributes after redirection in Spring MVC 3.1?

I would like to know how to read a flash attributes after redirection in Spring MVC 3.1.

I have the following code:

@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");
  }

}

What I am missing?

question from:https://stackoverflow.com/questions/11763779/how-to-read-flash-attributes-after-redirection-in-spring-mvc-3-1

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use Model, it should have flash attributes prepopulated:

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

or, alternatively, you can use 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
  }
}

P.S. You can do return return new ModelAndView("redirect:/foo/bar"); in handlePost.

EDIT:

JavaDoc says:

A RedirectAttributes model is empty when the method is called and is never used unless the method returns a redirect view name or a RedirectView.

It doesn't mention ModelAndView, so maybe change handlePost to return "redirect:/foo/bar" string or RedirectView:

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

I use RedirectAttributes in my code with RedirectView and model.asMap() method and it works OK.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...