如何在Spring MVC中的同一页上显示错误消息 [英] How to show error message on same page in spring MVC

查看:100
本文介绍了如何在Spring MVC中的同一页上显示错误消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Spring MVC中使用表单数据调用控制器.

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

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

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.

我在Internet上找到了一些示例,可以在发生任何错误的情况下重定向到故障jsp.但是,就我而言,该怎么做?

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?

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

推荐答案

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

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

然后,您的jsp可以显示错误"属性(如果存在).

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

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

编辑

这是通过ajax进行的未经验证的粗略实现.假设使用JQuery.

Edit

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

添加一个请求映射以使ajax命中:

Add a request mapping for the ajax to hit:

@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;

});

这篇关于如何在Spring MVC中的同一页上显示错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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