In my current spring project, when I submit a form to server, the response is handled by this method:
$('form.form').each(function () {
var form = this;
$(form).ajaxForm(function (data) {
form.reset();
$(".alert-info").find("#alert").html(data);
$(".alert-info").show();
});
});
In my controller, the submission is handled by a method like this:
@RequestMapping(value="cadastra", method=RequestMethod.POST)
@ResponseBody
@ResponseStatus(HttpStatus.CREATED)
public void cadastra(@ModelAttribute("object") E object, BindingResult result, @RequestParam(value="file", required=false) MultipartFile file, @RequestParam(value="icone", required=false) MultipartFile icone, @RequestParam(value="screenshot", required=false) MultipartFile screenshot[]) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, IOException {
serv.cadastra(object);
serv.upload_picture(object, file, "picture");
serv.upload_picture(object, icone, "icone");
}
Error responses from the methods from the controller are handled by this ControllerAdvice class:
@ControllerAdvice
@PropertySource({"classpath:error.properties"})
public class GlobalDefaultExceptionHandler {
@Autowired
private Environment env;
@ExceptionHandler(value = Exception.class)
public ModelAndView defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
// If the exception is annotated with @ResponseStatus rethrow it and let
// the framework handle it - like the OrderNotFoundException example
// at the start of this post.
// AnnotationUtils is a Spring Framework utility class.
if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null)
throw e;
// Otherwise setup and send the user to a default error-view.
ModelAndView mav = new ModelAndView();
mav.addObject("exception", e);
mav.addObject("url", req.getRequestURL());
mav.addObject("msg", e.getLocalizedMessage());
mav.setViewName("erro");
return mav;
}
}
I am looking for a way to read the http status code from response (which can be 1xx, 2xx, 3xx, 4xx or 5xx) in my jquery code, and display a related message according to this code.
In the network monitor from browser, I can see a successful response already have the code HTTP 201 as implemented in the method; when an error occurs, the response should have a code 4xx or 5xx, depending from exception triggered.
In this way, I wonder if anyone can give a hint of how modify my jquery code and my COntrollerAdvice to accomplish this.