我是 Spring 新手,我的其他 Controller 运行良好,但当我尝试调用 getmyfriends
端点时,我收到 405 Method Not Allowed
:
@Controller
@Path("friends")
public class FreindsJersey {
@Autowired
private FriendsService friendsService;
@POST
@Path("getmyfriends")
@Produces(MediaType.APPLICATION_JSON)
public Response getAllMyFriends(String json) {
ReturnData returnData = (ReturnData) Parser.getJsonFromString(json, ReturnData.class);
return Response.ok(friendsService.getMyFriendsList(returnData).getContainer()).build();
}
@GET
@Path("unfriend/{userId}/{friendId}")
@Produces(MediaType.APPLICATION_JSON)
public Response unfriendUser(@PathParam("userId") long userId, @PathParam("friendId") long friendId) {
return Response.ok(friendsService.deleteAFriendOfTheUser(userId, friendId).getContainer()).build();
}
}
最佳答案
TL;DR:getAllMyFriends
需要 POST
当您在浏览器中输入 URL 时,它将使用 GET
。您无法从 URL 栏POST
。
您的代码仅允许POST
。
@POST // <-- here
@Path("getmyfriends")
@Produces(MediaType.APPLICATION_JSON)
public Response getAllMyFriends(String json) {
ReturnData returnData = (ReturnData) Parser.getJsonFromString(json, ReturnData.class);
return Response.ok(friendsService.getMyFriendsList(returnData).getContainer()).build();
}
<小时/>
事实上,你把它搞反了 - safe and idempotent请求应该是GET
(例如getAllMyFriends
); 不安全和非幂等请求应为POST
(例如unfriendUser
)。
关于java - spring mvc 中不允许 405 方法,但其他操作和 Controller 工作正常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39094066/