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??????
}
}
A simple approach would be to add your error message as a model attribute. Then your jsp can display the "error" attribute if it exists.
[ BindingResult ] is Spring's object that holds the result of the validation and binding and contains errors that may have occurred. The BindingResult must come right after the model object that is validated or else Spring will fail to validate the object and throw an exception.
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>
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;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With