【问题标题】:Spring MVC Redirect Attribute MessagesSpring MVC 重定向属性消息
【发布时间】:2014-09-07 13:36:48
【问题描述】:

在我成功或未成功执行某种类型的 CRUD 操作(CREATE、DELETE 等)后,我在显示消息时遇到了一些问题。我曾尝试使用 Redirect Flash Attributes,但我发现这些都没有运气,而且我根本无法显示消息。例如,我在 Controller 方法中声明了这样的内容:

public String DeleteAction(Model model, Object object, @RequestParam int id, RedirectAttributes attributes) {
   // Method logic
   object.delete(id);
   attributes.addFlashAttribute("success", "Object has been removed successfully.");
   return "index"; // View resolver redirect
}

这是我在其中一个控制器中声明要绑定到视图的 flash 属性的函数示例。我在 .jsp ${success} 中像这样调用 flash 属性,尽管我仍然无法显示它。有什么我遗漏的东西不能让它工作吗?

【问题讨论】:

  • 为什么你不返回“redirect:”+“index”? flash 属性的使用是应该的。
  • 因为我认为您可以只返回“视图”并让视图解析器处理其余部分,尽管考虑到它不是重定向只是映射到新视图,这可能是问题所在。但是,我已经尝试过return "redirect: index",它也没有工作,所以我仍然不清楚为什么。除非我确实需要在那里添加“+”符号,对吗?
  • @Maff 已发布答案,如果对您有帮助
  • 不,你不需要 +,Maff。如果你真的有空格,你可以试着省略它吗?我的意思是'返回“重定向:索引”; ' 重定向在任何情况下都有效吗?

标签: java spring spring-mvc jstl


【解决方案1】:

Model 接口的特殊化,controllers 可以使用它来选择重定向场景的属性。由于添加redirect attributes 的意图非常明确——即用于redirect URL

@RequestMapping(value = "/delete", method = RequestMethod.GET)
public String DeleteAction(Model model, Object object, @RequestParam int id RedirectAttributes attributes) {
    object.delete(id);
    attributes.addFlashAttribute("success", "Object has been removed successfully.");
    return "redirect:" + "index";
}

【讨论】:

  • 我会尝试这个代码段并相应地为您提供一些反馈。我可以使用c:if 语句有条件地检查闪存属性对象“成功”并检查它是否为空吗?
  • 确认这对我有用。我仍然会在不提供“+”符号的情况下尝试这个,只需要return "redirect: index";
  • value = "/delete", method = RequestMethod.GET - 应该发布!!!获取仅用于幂等操作!只是我的 2 美分 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多