基于Spring MVC的站点(注释控制器)上的状态消息
问题内容:
使用注释控制器在基于Spring MVC的站点上组织状态消息(“您的数据已成功保存/添加/删除”)的最佳方法是什么?
因此,问题在于通过contoller中的POST方法发送消息的方式。
问题答案:
正如muanis所提到的,自3.1spring以来,最好的方法是使用RedirectAttributes。我将i18n添加到博客中给出的示例中。因此,这将是一个完整的示例。
@RequestMapping("/users")
@Controller
public class UsersController {
@Autowired
private MessageSource messageSource;
@RequestMapping(method = RequestMethod.POST, produces = "text/html")
public String create(@Valid User user, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest, Locale locale, RedirectAttributes redirectAttributes) {
...
...
redirectAttributes.addFlashAttribute("SUCCESS_MESSAGE", messageSource.getMessage("label_user_saved_successfully", new String[] {user.getUserId()}, locale));
return "redirect:/users/" + encodeUrlPathSegment("" + user.getId(), httpServletRequest);
}
...
...
}
在您的消息束中添加适当的消息,例如messages.properties。
label_user_saved_successfully=Successfully saved user: {0}
编辑您的jspx文件以使用相关属性
<c:if test="${SUCCESS_MESSAGE != null}">
<div id="status_message">${SUCCESS_MESSAGE}</div>
</c:if>