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!

有帮助吗?

解决方案

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();
    }
}

其他提示

you can make abstract controller with your loginModel and extends it for each controller you want to use login form in, this abstract controller should be without @Controller, all sub classes have to contain @Controller.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top