如何在 Spring MVC 3.1 中重定向后读取 flash 属性? [英] How to read flash attributes after redirection in Spring MVC 3.1?

查看:28
本文介绍了如何在 Spring MVC 3.1 中重定向后读取 flash 属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我有以下代码:

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

}

我缺少什么?

推荐答案

使用 Model,它应该预先填充 flash 属性:

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
}

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

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
  }
}

附言您可以在 handlePost 中执行 return return new ModelAndView("redirect:/foo/bar");.

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

编辑:

JavaDoc 说:

RedirectAttributes 模型在调用方法时为空,并且除非该方法返回重定向视图名称或重定向视图.

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.

它没有提到ModelAndView,所以可能改变handlePost 以返回"redirect:/foo/bar" 字符串或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);
}

我在我的代码中使用 RedirectAttributesRedirectViewmodel.asMap() 方法,它工作正常.

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

这篇关于如何在 Spring MVC 3.1 中重定向后读取 flash 属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆