Spring MVC中有多个@RequestMapping(值,方法对)

Phi*_*rer 1 java spring spring-mvc

我希望用Spring MVC实现这样的功能

@RequestMapping(value = "/user/{userId}", method =  RequestMethod.DELETE)
@RequestMapping(value = "/user/{userId}/delete", method = RequestMethod.POST)
public void deleteUser(@PathVariable String userId) {
    ...
}
Run Code Online (Sandbox Code Playgroud)

这将为我提供REST调用和标准HTML表单帖子的通用端点.是否可以使用Spring MVC?我能想出的就是

@RequestMapping(value = { "/user/{userId}", "/user/{userId}/delete"}, method =  {RequestMethod.DELETE, RequestMethod.POST})
public void deleteUser(@PathVariable String userId) {
    ...
}
Run Code Online (Sandbox Code Playgroud)

但结果略有不同,因为对"/ user/{userId}"的POST也会删除用户.

小智 5

你可以做的一件事是用他们自己的RequestMapping注释制作2个独立的方法,然后将参数传递给另一个方法,你可以在那里做实际的东西:

@RequestMapping(value = "/user/{userId}/delete", method = RequestMethod.POST)
public void deleteUserPost(@PathVariable String userId) {
    deleteUser(userId);
}

@RequestMapping(value = "/user/{userId}", method = RequestMethod.DELETE)
public void deleteUserDelete(@PathVariable String userId) {
    deleteUser(userId);
}

private void deleteUser(String userId){
    //Do things here
}
Run Code Online (Sandbox Code Playgroud)