RequestMapping Spring REST中的GET和POST方法处理

时间:2015-12-29 09:04:21

标签: spring rest spring-boot

我有这样的代码:

e.isInstance(e1)

我执行这样的@Configuration @ComponentScan @EnableAutoConfiguration public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } @RequestMapping(value = "/foo", method = RequestMethod.POST) String testPost(@RequestParam("param1") String param1, @RequestParam("param2") String param2) { return param1 + param2; } @RequestMapping("/foo") String testGet(@RequestParam String param1) { return param1; } } 表达式:

curl

curl --verbose http://localhost:9000/foo?param1=Sergei
* Hostname was NOT found in DNS cache
*   Trying 127.0.0.1...
* Connected to localhost (127.0.0.1) port 9000 (#0)
> GET /foo?param1=Sergei HTTP/1.1
> User-Agent: curl/7.35.0
> Host: localhost:9000
> Accept: */*
> 
< HTTP/1.1 404 Not Found
* Server Apache-Coyote/1.1 is not blacklisted
< Server: Apache-Coyote/1.1
< Content-Type: application/json;charset=UTF-8
< Transfer-Encoding: chunked
< Date: Tue, 29 Dec 2015 08:55:56 GMT
< 
* Connection #0 to host localhost left intact
{"timestamp":1451379356514,"status":404,"error":"Not Found","message":"No message available","path":"/foo"}

请帮助我,让我的方法都有效。

2 个答案:

答案 0 :(得分:1)

RestControllerController刻板印记注释添加到Application类,如下所示:

@RestController
@Configuration
@ComponentScan
@EnableAutoConfiguration
public class Application {
...
}

注意:您可以使用SpringBootApplication元注释而不是这三个,所以您可以:

@RestController
@SpringBootApplication
public class Application {
....
} 

答案 1 :(得分:1)

您应该将两个控制器方法的范围级别更改为public。现在,他们没有,所以这些方法默认为package local

public String testPost(@RequestParam("param1") String param1, @RequestParam("param2") String param2) {

public String testGet(@RequestParam String param1) {