romil gaurav
romil gaurav

Reputation: 1141

How to show error message on same page in spring MVC

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

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.

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

Upvotes: 10

Views: 51929

Answers (2)

tcosta
tcosta

Reputation: 151

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:

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

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

Hope it helps.

Upvotes: 7

Alex Wittig
Alex Wittig

Reputation: 2890

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.

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

Edit

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

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;

});

Upvotes: 18

Related Questions