Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring @RequestMapping absolute path

I've a RestController for a CRUD annotated like this:

@RestController
@RequestMapping("/rest/v1/area")
public class AreaController

My methods are annotated like:

@RequestMapping(value = "/{uuid}", method = RequestMethod.PUT)
public ResponseEntity<Area> save(@Valid @RequestBody Area area) {

Is there a way to use a value for a method to have an absolute path? I want to add a method to upload files, and don't want to make a new Controller just for this. I want a method like:

@RequestMapping(value = "/rest/v1/area-upload", method = RequestMethod.PUT
public String handleFileUpload(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) {

Thanks!

like image 317
Germán Avatar asked Aug 04 '16 14:08

Germán


People also ask

What does @RequestMapping do in spring?

One of the most important annotations in spring is the @RequestMapping Annotation which is used to map HTTP requests to handler methods of MVC and REST controllers. In Spring MVC applications, the DispatcherServlet (Front Controller) is responsible for routing incoming HTTP requests to handler methods of controllers.

What is the @RequestMapping annotation used for?

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.

What is path in @RequestMapping?

this is the path property: This is an alias for path() . For example @RequestMapping("/foo") is equivalent to @RequestMapping(path="/foo") . The reasoning behind this is that the value element is the default when it comes to annotations, so it allows you to write code in a more concise way.

What is @RequestMapping and GetMapping?

@RequestMapping is used at the class level while @GetMapping is used to connect the methods. This is also an important Spring MVC interview question to knowing how and when to use both RequestMapping and GetMapping is crucial for Java developers.


2 Answers

From the documentation: (spring 2.5 api document of requestmapping)

Method-level mappings are only allowed to narrow the mapping expressed at the class level (if any)

So you cannot override, only narrow it down to sub-paths.

Ofcourse if you create a new controller class and put the method there, you can have it point to whatever path you like.

like image 81
Joeblade Avatar answered Sep 22 '22 15:09

Joeblade


You can just change route mapping for the controller.

@RestController
@RequestMapping("/rest/v1")
public class AreaController

and the mapping for method will be:

@RequestMapping(value = "/area-upload", method = RequestMethod.PUT
public String handleFileUpload(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) {
like image 43
Foredoomed Avatar answered Sep 26 '22 15:09

Foredoomed