springrest中的RequestMapping GET和POST方法处理
我有这样的代码:springrest中的RequestMapping GET和POST方法处理,spring,rest,spring-boot,Spring,Rest,Spring Boot,我有这样的代码: @Configuration @ComponentScan @EnableAutoConfiguration public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } @RequestMapping(value = "/foo", method = Reque
@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"}
curl——冗长http://localhost:9000/foo?param1=Sergei
*在DNS缓存中找不到主机名
*正在尝试127.0.0.1。。。
*已连接到本地主机(127.0.0.1)端口9000(#0)
>GET/foo?param1=Sergei HTTP/1.1
>用户代理:curl/7.35.0
>主机:localhost:9000
>接受:*/*
>
未找到
以及
curl--verbose--data“param1=value1¶m2=value2”http://localhost:9000/foo
*在DNS缓存中找不到主机名
*正在尝试127.0.0.1。。。
*已连接到本地主机(127.0.0.1)端口9000(#0)
>POST/foo HTTP/1.1
>用户代理:curl/7.35.0
>主机:localhost:9000
>接受:*/*
>内容长度:27
>内容类型:application/x-www-form-urlencoded
>
*上传已完全发送:27个字节中的27个
请帮我让我的两种方法都起作用 向
应用程序
类添加RestController
或Controller
原型注释,如下所示:
@RestController
@Configuration
@ComponentScan
@EnableAutoConfiguration
public class Application {
...
}
注意:您可以使用SpringBootApplication
元注释而不是这三种注释,因此您可以:
@RestController
@SpringBootApplication
public class Application {
....
}
您应该将这两个控制器方法的作用域级别更改为
public
。现在,他们没有任何方法,因此默认情况下方法是packagelocal
publicsstringtestpost(@RequestParam(“param1”)stringparam1,@RequestParam(“param2”)stringparam2){
publicstringtestget(@RequestParam stringparam1){
问题在于应用程序甚至不是控制器(或者RestController
),因此更改可见性不会有任何影响。顺便说一句,默认的可见性是包本地
不受保护
。对不起,我的坏-将纠正它。顺便问一下,更改为公共帮助了吗?他应该为他的应用程序
添加一个RestController
注释。哦,是的,刚刚看到他甚至失踪了RestController
注释。@ketan、public
或package local
不重要。我已经检查过了
@RestController
@SpringBootApplication
public class Application {
....
}