在Spring引导中启用HTTP请求POST

在Spring引导中启用HTTP请求POST,spring,spring-mvc,spring-boot,Spring,Spring Mvc,Spring Boot,我使用的是SpringBoot,这里是maven依赖项 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> 在响应头中 HTTP/1.1 405 Method Not Allowed Ser

我使用的是SpringBoot,这里是maven依赖项

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
在响应头中

HTTP/1.1 405 Method Not Allowed
Server: Apache-Coyote/1.1
X-Application-Context: application
Allow: HEAD, GET
Content-Type: application/json;charset=UTF-8
Transfer-Encoding: chunked
Date: Wed, 09 Jul 2014 13:04:05 GMT
我意识到在响应中allow没有POST方法

控制器中的方法

@RequestMapping(value = "/xxxx/{uid}/addEntry", method = RequestMethod.POST)
@ResponseBody
public String createEntry(@PathVariable String uid, @RequestBody  String form) {
    System.out.println(form);
    return "index.html";
}

这是一段时间以前的事了,很抱歉当时没有发布答案,但我会尝试解释我认为发生了什么

我曾试图用Chrome Postman插件测试ajax请求,但因为我遇到了CORS问题而无法实现(我无法用POST方法测试ajax,因为服务器只允许我发出HEAD或GET请求)

在同一台服务器上,我有angular应用程序(必须发出POST请求的应用程序)和JavaAPI(需要POST请求的应用程序),因此,我没有CORS问题。但它不起作用,因为我犯了另一个错误,那就是在角度应用程序的post方法中,我没有在post上发送有效负载数据

@RequestMapping(value = "/xxxx/{uid}/addEntry", method = RequestMethod.POST)
@ResponseBody
public String createEntry(@PathVariable String uid, @RequestBody  String form) {
    System.out.println(form);
    return "index.html";
}

我希望这能使答案更清楚。谢谢你的阅读。

一个不同的解决方案对我有效。我只需要向控制器本身添加适当的注释,如下所示:

@RestController
public class EntriesController {
    //your code here
}

有时,特别是在初始测试期间,Spring的csrf-跨站点请求伪造-保护在默认情况下起作用,并防止POST请求发生,一个临时解决办法是禁用csrf。这通常在扩展WebSecurity配置适配器的Web安全配置类中完成

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf().disable();
    }
}

注意:这与Spring boot版本2.0.0.RC1的工作原理相同,如果此未被用作永久性解决方案,则其效果最好

Spring boot默认启用CSRF安全性。当通过JS提交表单数据时,在发布到端点时,您需要包含Spring引导生成的_csrf令牌。

您确定Spring看到了控制器吗?该控制器的其他方法有效吗?@axtavt感谢您的回答。GET请求正在工作。如果尝试删除
@RequestBody字符串表单
,该怎么办?@axtavt谢谢,现在POST请求正在工作。你的评论帮助我认识到了这个问题。我没有在POST请求中发送有效负载。那么你能回答你自己的问题吗?对不起,但这个答案不能解释任何事情。@SergDerbst对此表示抱歉,我希望这个解释能有所帮助
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf().disable();
    }
}