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

时间:2015-04-01 12:23:31

标签: 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) {
    ...
}

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

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

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

2 个答案:

答案 0 :(得分: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
}

答案 1 :(得分:4)

对不起,错误的方法。

mature REST architecture中,代码应使用URL来引用资源,并使用HTTP方法定义资源上的操作。所以只需定义一个@RequestMapping("/user/{userId}/delete", method = RequestMethod.DELETE)并取消POST。请参阅DELETE vs POST