Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Controllers: Can I call a method before each @RequestMapping method is called?

Tags:

I have some common components that are always present in every page served by a given Controller class.

At the beginning of each @RequestMapping method I populate the model with these common components.

Is there a way to define a method be called prior to each of the controller methods so that I can get all of this copy/paste into one place?

like image 554
David Parks Avatar asked Feb 23 '11 07:02

David Parks


People also ask

Is @RequestMapping mandatory?

A @RequestMapping on the class level is not required. Without it, all paths are simply absolute, and not relative.

What is true about @RequestMapping annotation in Spring MVC?

The @RequestMapping annotation can be applied to class-level and/or method-level in a controller. The class-level annotation maps a specific request path or pattern onto a controller. You can then apply additional method-level annotations to make mappings more specific to handler methods.

What will happen if handler methods @RequestMapping?

In the code snippet above, the method element of the @RequestMapping annotations indicates the HTTP method type of the HTTP request. All the handler methods will handle requests coming to the same URL ( /home), but will depend on the HTTP method being used.


1 Answers

Just annotate a method with @ModelAttribute

The below would add a Foo instance to the model under the name "foo"

@ModelAttribute("foo") public Foo foo() {     return new Foo(); } 

See the @ModelAttribute documentation

like image 128
ptomli Avatar answered Nov 15 '22 11:11

ptomli