Showing posts with label Annotation. Show all posts
Showing posts with label Annotation. Show all posts

Saturday, September 14, 2013

Spring 3.2 @ControllerAdvice to handle Controller Exceptions

My Java/Spring web application has controllers that either return ModelAndView to a jsp page or return json for ajax calls.  Exceptions can occur at any time, and I noticed that on ajax success the data returned was json, but on ajax error the data returned was regular text; all ajax calls should return the same kind of data, namely json.  There had to be a way to solve this problem generically!

Spring 3.2 to the rescue - it introduced a new annotation called @ControllerAdvice (http://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/new-in-3.2.html#new-in-3.2-webmvc-controller-advice)  that defines methods that applies to all @RequestMapping rest url methods, and in particular to help with exceptions with @ExceptionHandler.  We can use this to have a generic exception handling solution to have all ajax calls return json, and all ModelAndView return html.

  • @ControllerAdvice allows you to define ONE controller class to handle ALL exceptions that could occur (no specific exceptions defined needed)
  • You can control the HTTP status code returned
  • You can control the json message returned by grabbing the exception message from the specific exception that occurred

Here's how you do it:
  1. Your controllers won't change, the code will still continue to throw any number of specific exceptions:
  2. @Controller
    public class ExceptionController {
        
        @RequestMapping(value = "/randomException", method = RequestMethod.GET)
        public String randomException(Authentication auth, HttpServletRequest request) throws Exception {    
           
            throw new NumberFormatException(" " +
                    "Test ControllerAdvice randomException[" + "NumberFormatException" + "]");
    
            [...]
        }
    
        @RequestMapping(value = "/mavException", method = RequestMethod.GET)   
        public ModelAndView modelAndViewException(Authentication auth, HttpServletRequest request) throws Exception {  
         
            throw new UnexpectedRollbackException("Test ControllerAdvice Exception for mav");
            [...]
        }
    }
    
  3. Write ONE new Controller, this will act as your ControllerAdvice controller. Notice:
    • the class is annotated with @ControllerAdvice
    • @ExceptionHandler is annotated above your generic "handleException" function
    • handleException function takes generic Exception e as a parameter
    • it checks the accept header to see how the controller function was invoked (via ajax or via form submit; randomException or mavException, respectively).  *Update*  We have to check for null first in case the request doesn't specify a response type expected.  If the request doesn't specify it, then simply return text/html.
    • It returns json or html
    • @ControllerAdvice
      public class CherryShoeControllerAdvice {
      
          /*
           * Handles JSON and HTML
           */
          @ExceptionHandler
          @ResponseBody
          @ResponseStatus(HttpStatus.BAD_REQUEST)
          public String handleException(HttpServletRequest request, HttpServletResponse response, Exception e) throws IOException {    
              String acceptHeader = request.getHeader("Accept");
             
              // If Accept header exists, check if it expects a response of type json, otherwise just return text/html
              // Use apache commons lang3 to escape json values
              if(acceptHeader.contains("application/json")) {
                  // return as JSON
                  String jsonString = 
                          "{\"success\": false, \"message\": \"" + StringEscapeUtils.escapeJson(e.getMessage()) + "\" }";
              
                  System.out.println("In handleGeneric" + e.getMessage());
                  return jsonString;
              } else {
                  //return as HTML
                  response.setContentType("text/html");
                  return response.toString();
              }
          }
      
      }
      

BTW - if you wanted to specify each type of exception going to a separate @ExceptionHandler you could.

BTW - The main cons for using pre-Spring 3.2 @ExceptionHandler (http://docs.spring.io/spring/docs/3.1.x/spring-framework-reference/html/mvc.html#mvc-exceptionhandlers) by itself are you have to:

  • Define an ExceptionHandler for EACH controller (or have each controller inherit from one common base)
  • Define EACH exception type to be handled – Or have each controller throw the specific type of exception expected


Saturday, August 25, 2012

HOW TO: Make file uploads work with WizardPro jQuery Library and Spring MVC 3.0


My web application front-end code is built using HTML5, CSS3, and jQuery, using the Spring MVC 3.0 Framework to get back-end data back to the browser. We use the WizardPro jQuery library to aid the user in creating objects in the webapp (WizardPro is a great little jQuery library that enables you to create an object in a few steps).

Here is where my heartache comes in – WizardPro’s default form submit uses XMLHttpRequest. Don’t get me wrong, most of the time the default behavior works great! Specifically, it doesn’t work is when you need file uploads in your web app, therefore requiring an input type of file as a form control. Luckily, Spring MVC 3.0 fileupload support was available in our toolkit already (it provides a MultipartResolver for use with Apache Commons FileUpload). To be able to make file uploads work with WizardPro and Spring MVC file upload, you must do the following:

1.  For the Spring MultipartHttpServletRequest to work, set WizardPro’s  defaultAjaxRequest attribute to false when the wizard is instantiated.
$("#wizard").wizardPro({
defaultAjaxRequest: false
,...
});
2.  WizardPro uses a default form class called .defaultRequest, this makes sure the plugin handles the default form ajax requests submits and validation.  Make a copy of the .defaultRequest CSS classes and name it uniquely, i.e. .defaultRequest2.  In the form tag, set the class to this new class name, so the class will not bind wizardPro to use default ajax submits.  Instead WizardPro will use normal HTML form submits with the file input form control for file uploads.

BAD:
<form class=”defaultRequest” action=”someUrl” method=”post” enctype=”application/x-www-form-urlencoded”>

GOOD:
<form class=”defaultRequest2” action=”someUrl” method=”post” enctype=”multipart/form-data“>

3.  Set the encode type to multipart/form-data in the form tag, MultipartHttpServletRequest filter expects this.  Example in number 2 above.

When you follow the above steps, along with setting up Spring MVC’s multipartResolver in the servlet context spring configuration file, ensuring the form action URL and the controller @RequestMapping match, etc, then WizardPro and file uploads work great together!

P.S.  You may ask me, “Why not use an HTML5/AJAX supported file upload library?”.  Uploadrr is a great little library that does this, and I’ve tested it using Firefox 3 and Chrome 10, with both @RequestParam using MultipartFile and also with the HttpServletRequest Input Stream to get the file byte data.  Unfortunately, it does not work for our primary browser platform, IE8, which is why (for now at least), we can’t integrate this into the webapp.