Spring MVC PUT Request returns 405 Method Not Allowed

前端 未结 6 1998
庸人自扰
庸人自扰 2020-12-19 02:27

I am using spring mvc to set up a rest api and most of the configurations are set up automatically through the spring boot project. On the front end I am using angularjs and

6条回答
  •  遥遥无期
    2020-12-19 03:00

    Your problem is that the endpoints for findById and updateUser are the same which is api/users/{id} and since the one with GET method comes first it will be evaluated first when you send a PUT request and hence will be rejected by spring.

    I suggest you change the endpoint for updating user to api/users/update/{id} as below:

    @Controller
    @RequestMapping("/api/users")
    public class UserController {
    
        @Inject
        UserService svc;
    
        @RequestMapping(method = RequestMethod.GET)
        @ResponseBody
        public List home() {
            return svc.findAll();
        }
    
        @RequestMapping(method = RequestMethod.GET, value = "/{id}")
        @ResponseBody
        public User findById(@PathVariable long id){
            return svc.findById(id);
        }
    
        @RequestMapping(method = RequestMethod.PUT, value="/update/{id}")
        @ResponseBody
        public User updateUser(@PathVariable long id, @RequestBody User user){
            Assert.isTrue(user.getId().equals(id), "User Id must match Url Id");
            return svc.updateUser(id, user);
        }
    
    }
    

提交回复
热议问题