2014-07-09 264 views
7

启用HTTP POST请求我使用Spring启动,这里的行家依赖在春季启动

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

对于网页,我把文件放在src /主/资源/静态的。在那里我有我的html文件,js库(angular,jquery)和css文件。

我试图与角的HTTP请求POST(我也有做工精细的GET请求),但我得到这个

POST http://localhost:8080/xxxx/12/addEntry 405 (Method Not Allowed) 

在响应头

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 

我意识到在Response中,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"; 
} 
+0

你确定Spring看到控制器吗?该控制器的其他方法是否工作? – axtavt

+0

@axtavt谢谢你的回答。 GET请求正在工作。 – agusgambina

+8

如果您尝试删除'@RequestBody字符串表单',该怎么办? – axtavt

回答

1

有时候,尤其是在初始测试Spring的CSRF - 跨站请求伪造 - 保护踢在默认情况下,防止POST请求的发生,临时解决方法是禁用csrf。这是在一个延伸WebSecurityConfigurerAdapter

@EnableWebSecurity 
public class WebSecurityConfig extends WebSecurityConfigurerAdapter { 

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

注意您的Web安全配置类典型的做法:这个工程作为春天引导版本2.0.0.RC1其最好的,如果这个IS NOT作为长期工作大约

0

这是前一阵子,很抱歉没有张贴当时的答案,但我会尽量解释什么,我想这件事已经发生的方法。

我试图用Chrome邮差插件测试ajax请求,但不可能,因为我有一个CORS问题(我不能用POST方法做ajax,因为服务器只允许我做一个HEAD或GET请求)。

在同一台服务器上,我有角度应用程序(这是必须发出POST请求的应用程序)和Java API(这是期待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"; 
} 

我希望这能让答案更清楚。谢谢阅读。

+1

对不起,但这个答案没有解释任何东西。 –

+0

@SergDerbst对不起,我希望这个解释有帮助 – agusgambina

+0

太好了,谢谢! :) –

2

一个不同的解决方案为我工作。我只是需要适当的注释添加到控制器本身,就像这样:

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