Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Share a common parent path when implementing Spring controllers

I want to be able to define a parent Controller class which will have a mapping of "/api", and then extend that controller with my different implementations. So ApiController will have:

@Controller
@RequestMapping("/api")

For example, my User controller should extend the base api controller and also add "/users" to the path, so it will answer to "/api/users" requests. So UserController will have:

@Controller
@RequestMapping("/users")

but since it extends ApiController, it will effectively answer to /api/users.

Naturally I can prepend "/api" to all controllers so that this is achieved without the parent class, but I prefer to do it "the right way" if it's possible, so that I can define my api implementations with a cleaner and more visible path.

I tried extending the ApiController base class, but this does not work, UserController still answers to "/users" and ignores the base class "/api".

like image 592
TheZuck Avatar asked Aug 12 '12 13:08

TheZuck


People also ask

What are the responsibilities of controller in spring?

In Spring MVC, controller methods are the final destination point that a web request can reach. After being invoked, the controller method starts to process the web request by interacting with the service layer to complete the work that needs to be done.

Can we have 2 controller class in spring boot?

In Spring MVC, we can create multiple controllers at a time. It is required to map each controller class with @Controller annotation.

What is @RequestMapping annotation in spring boot?

RequestMapping annotation is used to map web requests onto specific handler classes and/or handler methods. @RequestMapping can be applied to the controller class as well as methods. Today we will look into various usage of this annotation with example and other annotations @PathVariable and @RequestParam .


1 Answers

Hmmm. You can try this, it is what works for me:

@RequestMapping("/abstract")
public abstract class AbstractController {


}

@Controller
public class ExtendedAbstractController extends AbstractController {

   @RequestMapping("/another")
   public String anotherTest() {
       return "another";
   }

}

Note, your base class must have no @Controller annotation and must be abstract.

If you try to do extend not abstract class annotated as controller and that has @RequestMappings you get errors on step where RequestMappingHandlerMapping initializing.

like image 52
masted Avatar answered Nov 13 '22 09:11

masted