基于 Spring MVC 的站点(注解控制器)上的状态消息 [英] Status messages on the Spring MVC-based site (annotation controller)
问题描述
使用注解控制器在基于 Spring MVC 的站点上组织状态消息(您的数据已成功保存/添加/删除")的最佳方法是什么?
What is the best way to organize status messages ("Your data has been successfully saved/added/deleted") on the Spring MVC-based site using annotation controller?
因此,问题在于控制器中从 POST 方法发送消息的方式.
So, the issue is in the way of sending the message from POST-method in contoller.
推荐答案
正如 muanis 所提到的,从 spring 3.1 开始,最好的方法是使用 RedirectAttributes.我在博客中给出的示例中添加了 i18n.所以这将是一个完整的样本.
As mentioned by muanis, since spring 3.1, the best approach would be to use RedirectAttributes. I added i18n to the sample given in the blog. So this would be a complete sample.
@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.
Add appropriate message in your message bundle, say messages.properties.
label_user_saved_successfully=Successfully saved user: {0}
编辑您的 jspx 文件以使用相关属性
Edit your jspx file to use the relevant attribute
<c:if test="${SUCCESS_MESSAGE != null}">
<div id="status_message">${SUCCESS_MESSAGE}</div>
</c:if>
这篇关于基于 Spring MVC 的站点(注解控制器)上的状态消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!