小编典典

Spring MVC PUT请求返回405方法不允许

spring-boot

我正在使用spring mvc设置rest api,并且大多数配置是通过spring boot项目自动设置的。在前端,我正在使用angularjs及其$
http模块向服务器发出ajax请求以获取资源。资源URL在我的控制器类中定义,但是只有GET
URL被匹配。我已经尝试了PUT和POST,但是分别不允许返回405方法和403禁止。

我的控制器看起来像这样

@Controller
@RequestMapping("/api/users")
public class UserController {

    @Inject
    UserService svc;

    @RequestMapping(method = RequestMethod.GET)
    @ResponseBody
    public List<User> 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="/{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);
    }

}

并且对与网址不匹配的服务器的请求如下所示

$http({
            url: BASE_API + 'users/' + user.id,
            method: 'PUT',
            data:user
        })

这会向localhost:8080 / api / users / 1产生一个PUT请求,并且服务器使用405 Method Not
Allowed响应代码进行响应。

当服务器收到对localhost:8080 / api / users / 1的HTTP
GET请求时,可以正确处理具有RequestMethod.GET的相同请求映射

任何见解都会有所帮助。

PS,如果需要的话,包括的spring boot依赖项是

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
        <scope>provided</scope>
    </dependency>

谢谢


阅读 268

收藏
2020-05-30

共1个答案

小编典典

查看日志(安全性在DEBUG上),您将发现问题。您很可能没有禁用csrf保护,并且客户端没有发送csrf令牌。(标准Spring
Security,而不是Spring Boot,尽管如果您使用Boot Security自动配置,则可以使用外部配置设置关闭csrf。)

2020-05-30