可以使用@PathVariable和@RequestMapping注释解决此问题。首先,在应用程序的Controller类中创建一个带有变量路径的方法。然后在请求映射中使用@RequestParam注释将参数传递给该方法。最后,使用@PathVariable注释获取PathVariable值并将其应用于相应的请求路径或servlet路径。
示例代码:
@RestController
public class MyController {
@RequestMapping(value = { "/api/{id}" }, method = RequestMethod.GET)
public ResponseEntity handleGetRequest(@PathVariable("id") String id) {
// handle GET request with variable path
return new ResponseEntity<>("Request with ID: " + id, HttpStatus.OK);
}
@RequestMapping(value = { "/api/user/{name}" }, method = RequestMethod.POST)
public ResponseEntity handleCtnRequest(@PathVariable("name") String name, @RequestBody MyRequest request) {
// handle POST request with variable path and request body
return new ResponseEntity<>("Created user: " + name + ", with request: " + request.toString(), HttpStatus.CREATED);
}
}