4

Let's say I have following controller.

@RestController()
@RequestMapping("/my/{path}")
public class MyController {

    public void some1(@PathVariable("path") String path) {
    }

    public void some2(@PathVariable("path") String path) {
    }

    public void some3(@PathVariable("path") String path) {
    }
}

Now I want the path be injected into a field.

// I usually do this with JAX-RS 
@RequestScope // I added this!
@RestController()
@RequestMapping("/my/{path}")
public class MyController {

    public void some1() {
    }

    public void some2() {
    }

    public void some3() {
    }

    // single declaration for all methods
    // I know ElementType.FIELD is not one of @PathVariable's target
    // Is there any equivalent way to do this with Spring?
    @PathVariable("path")
    String path
}

Not compiles.

How can I do this?

Jin Kwon
  • 20,295
  • 14
  • 115
  • 184

2 Answers2

-1

request url : /a/b/c

@RequestMapping(value = "/a/{some}/c")
public void some(@PathVariable("some") String some) {
}
syaku
  • 102
  • 1
  • 5
-2

@PathVariable Annotation which indicates that a method parameter should be bound to a URI template variable.

Examples :

@ResponseBody
RequestMapping(value="/myapp/{id}")
public String method(@PathVariable("id") int id){
 return "id="+id;
}
 

@ResponseBody
@RequestMapping(value="/myapp/{id:[\\d]+}/{name}")
public String method(@PathVariable("id") long id, @PathVariable("name") String name){
 return "id= "+id+" and name="+name;
}

Refer more for below links :

Spring mvc @PathVariable

https://www.journaldev.com/3358/spring-requestmapping-requestparam-pathvariable-example

Ramesh Fadatare
  • 561
  • 4
  • 12