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".
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.
In Spring MVC, we can create multiple controllers at a time. It is required to map each controller class with @Controller annotation.
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 .
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 @RequestMapping
s you get errors on step where RequestMappingHandlerMapping
initializing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With