Search code examples
jspspring-mvcjspxapache-tiles

Spring one ModelAttribute in several Controller


I develop in Spring MVC + Apache Tiles + JSPX in my system.

I would like to put login form in every page. In the login process I would like to use @ModelAttribute("loginModel") LoginDTO

In Spring docs page I red that I must define a method in every controller, where I want to display that model like this:

@ModelAttribute("loginModel")
public LoginDTO loginModel() {
   return new LoginDTO();
}

Is there any way that I define it only one controller, and works in every page where I write the login Form jsp?

Thanks your answare!


Solution

  • If you are using Spring 3.2 or later you can use the new @ControllerAdvice annotation. From the documentation of @ModelAttribute:

    @ModelAttribute methods can also be defined in an @ControllerAdvice-annotated class and such methods apply to all controllers. The @ControllerAdvice annotation is a component annotation allowing implementation classes to be autodetected through classpath scanning.

    In your case, I guess it would look something like:

    @ControllerAdvice
    public class GlobalControllerAdvice {
    
        @ModelAttribute("loginModel")
        public LoginDTO loginModel() {
            return new LoginDTO();
        }
    }