spring 如何在spring MVC的同一页面上显示错误消息

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22664533/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 06:37:54  来源:igfitidea点击:

How to show error message on same page in spring MVC

springjspspring-mvc

提问by romil gaurav

I am calling a controller in spring mvc with form data.

我正在使用表单数据调用 spring mvc 中的控制器。

Before saving, I check if the id is a certain range. If the id is not within the range, I need to show a message on the same page saying The id selected is out of Range, please select another id within range.

在保存之前,我会检查 id 是否在某个范围内。如果 id 不在范围内,我需要在同一页面上显示一条消息,说The id selected is out of Range, please select another id within range.

I found samples on internet where I can redirect to failure jsp in case anything goes wrong. But how to do it in my case?

我在互联网上找到了一些示例,如果出现任何问题,我可以重定向到失败的 jsp。但是在我的情况下怎么做呢?

@RequestMapping(value = "/sendMessage")
public String sendMessage(@ModelAttribute("message") Message message,
        final HttpServletRequest request) { 
    boolean check = userLoginService.checkForRange(message.getUserLogin());
    if(!check){
        return "";  //What Should I do here??????
    }
}

回答by Alex Wittig

A simple approach would be to add your error message as a model attribute.

一种简单的方法是将错误消息添加为模型属性。

@RequestMapping(value = "/sendMessage")
public String sendMessage(@ModelAttribute("message") Message message,
        final HttpServletRequest request, Model model) {

    boolean check = userLoginService.checkForRange(message.getUserLogin());
    if(!check){
        model.addAttribute("error", "The id selected is out of Range, please select another id within range");
        return "yourFormViewName";
    }
}

Then your jsp can display the "error" attribute if it exists.

然后您的 jsp 可以显示“错误”属性(如果存在)。

<c:if test="${not empty error}">
   Error: ${error}
</c:if>

Edit

编辑

Here's a rough, untested implementation of validation over ajax. JQuery assumed.

这是一个粗略的、未经测试的 ajax 验证实现。JQuery 假设。

Add a request mapping for the ajax to hit:

为 ajax 添加一个请求映射来命中:

@RequestMapping("/validate")
@ResponseBody
public String validateRange(@RequestParam("id") String id) {

    boolean check = //[validate the id];
    if(!check){
        return "The id selected is out of Range, please select another id within range";
    }
}

Intercept the form submission on the client side and validate:

拦截客户端提交的表单并验证:

$(".myForm").submit(function(event) {

    var success = true;

    $.ajax({
        url: "/validate",
        type: "GET",
        async: false, //block until we get a response
        data: { id : $("#idInput").val() },
        success: function(error) {
            if (error) {
                $("#errorContainer").html(error);
                success = false;
            }
        }
    });

    return success;

});

回答by tcosta

You can also use the existing error messages support. This way you can use the spring-mvc error tags to show the error at a global context or even at the field level. For example, if you pretend to bind the error to the field, you can use:

您还可以使用现有的错误消息支持。通过这种方式,您可以使用 spring-mvc 错误标签在全局上下文甚至字段级别显示错误。例如,如果您假装将错误绑定到字段,则可以使用:

@RequestMapping(value = "/sendMessage")
public String sendMessage(@ModelAttribute("message") Message message, BindingResult bindingResult) {
    boolean check = userLoginService.checkForRange(message.getUserLogin());
    if (!check) {
        bindingResult.rejectValue("userLogin", "error.idOutOfRange", "The id selected is out of Range, please select another id within range");
        return "jspPage"; // path to the jsp filename, omit extension (considering default config) 
    }
}

At the page level, you can do:

在页面级别,您可以执行以下操作:

<form:form method="POST" commandName="message">
    ...
    <form:input path="userLogin" />
    <form:errors path="userLogin" />
    ...
</form:form>

If you just want to show a global error, omit the parameter name at bindingResult.rejectValue and form:errors tag.

如果您只想显示全局错误,请省略 bindingResult.rejectValue 和 form:errors 标记处的参数名称。

Note: you do not need to worry about recovering parameters manually. In normal conditions, spring-mvc will handle that for you.

注意:您无需担心手动恢复参数。在正常情况下,spring-mvc 会为你处理。

Hope it helps.

希望能帮助到你。