Implementing common features using the @ControllerAdvice annotation

Some of the functionality we defined at the controller level can be common across the application. For example, we may want to use the same date format across the application. So, @InitBinder, which we defined earlier, can be applied across the application. How do we achieve that? @ControllerAdvice helps us to make the functionality common across all RequestMapping by default.

For example, consider the Controller advice example listed here. We use an @ControllerAdvice annotation on the class and define the method with @InitBinder in this class. By default, the binding defined in this method is applicable to all request mappings:

    @ControllerAdvice 
public class DateBindingControllerAdvice {
@InitBinder
protected void initBinder(WebDataBinder binder) {
SimpleDateFormat dateFormat = new
SimpleDateFormat("dd/MM/yyyy");
binder.registerCustomEditor(Date.class,
new CustomDateEditor(
dateFormat, false));
}
}

Controller advice can also be used to define common model attributes (@ModelAttribute) and common exception handling (@ExceptionHandler). All you need to do is to create methods marked with appropriate annotations. We will discuss exception handling in the next section.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset