Spring Boot Web:限定某个URL的请求方法


#Spring Boot#


示例

基于 Spring Boot Web:通过 Hello World 入门 中的示例代码稍作更改。

项目结构:

├── build.gradle
└── src
    └── main
        ├── java
        │   └── hello
        │       ├── Application.java
        │       ├── Greeting.java
        │       └── GreetingController.java
        └── resources

特定 URL 只允许某个 HTTP 方法

例如,针对某个URL,只允许POST方法,可以这样做:

在 GreetingController 类中增加:

@RequestMapping(value = "/greeting2", method = RequestMethod.POST)
public Greeting greeting2(@RequestParam(value="name", defaultValue="World") String name) {
    return new Greeting(counter.incrementAndGet(),
            String.format("Hello, %s!", name));
}

使用浏览器测试

浏览器访问 http://localhost:8090/greeting2?name=World ,报错“Whitelabel Error Page”,因为浏览器默认用的是 GET 方法。

使用 postman 测试

使用 postman 构造POST请求到http://localhost:8080/greeting2,请求体是:

name=Spring

响应为:

{"id":4,"content":"Hello, Spring!"}

使用 curl 测试

或者使用 curl 进行 POST 请求:

curl -d "name=Spring" "http://127.0.0.1:8080/greeting2"

响应为:

{"id":1,"content":"Hello, Spring!"}

特定 URL 允许多个 HTTP 方法

如果要支持多种方法,例如支持POST和PUT,可以这样子:

@RequestMapping(value = "/greeting2", method = {RequestMethod.POST, RequestMethod.PUT})

( 本文完 )