Build a Restful Web Service
这篇文章将完成使用Spring创建“Hello,World” restfulweb服务的过程。
使用IDEA作为开发工具,使用Maven进行项目管理。
Starting with Spring Initialize
首先从Spring Initializr快速创建项目restservice,这里只需要添加Spring Web依赖。
点击Generate将项目下载到本地。
Create a Resource Representation Class
在src/main/java/com/example/restservice/目录下新建Greeting.java文件。
package com.example.restservice;
public class Greeting {
private final long id;
private final String content;
public Greeting(long id, String content) {
this.id = id;
this.content = content;
}
public long getId() {
return id;
}
public String getContent() {
return content;
}
}
Create a Resource Controller
在目录src/main/java/com/example/restservice/下创建GreetingController.java文件。
package com.example.restservice;
import java.util.concurrent.atomic.AtomicLong;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class GreetingController {
private static final String template = "Hello, %s!";
private final AtomicLong counter = new AtomicLong();
@GetMapping("/greeting")
public Greeting greeting(@RequestParam(value = "name", defaultValue = "World") String name) {
return new Greeting(counter.incrementAndGet(), String.format(template, name));
}
}
Test the Service
到这里就可以测试service了,运行main函数。在浏览器打开http://localhost:8080/greeting,可以看到如下结果。
同时我们可以提供name参数,在地址栏输入http://localhost:8080/greeting?name=FZQ,可以看到“Hello,World"变成了"Hello,FZQ"。
Summary
在这里主要对过程中用到的注解进行总结
@RestController
一个很方便的注解,自身包含了 @Controller 和 @ResponseBody。
带有这个注解的类型被视为控制器,其中 @RequestMapping 方法默认使用 @ResponseBody 的语义。
@GetMapping
@GetMapping 确保对 /greeting 的 HTTP GET 请求被映射到greeting()方法。
其他HTTP动作也有相应的注解,如POST请求有 @PostMapping 注解。 他们都是从 @RequestMapping 派生而来的,有着相同的作用,如 @RequestMapping(method=GET) 。
@RequestParam
@RequestParam 将 query string parameter name 的值绑定到greeting()方法的name参数中。如果请求中缺少name参数,则会使用默认的参数“World”。
@SpringBootApplication
@SpringBootApplication 是一个很方便的注解,包含了以下所有注解:
@Configuration:将该类标记为bean定义的源。
@EnableAutoConfiguration:告诉Spring Boot基于类的路径设置、其他bean和各种属性设置添加bean。例如,如果spring-webmvc 在类的路径上,这个注解就会将这个应用程序标记为web应用程序,并激活关键行为,例如建立一个DispatcherServlet。
@ComponentScan:告诉Spring在com/example包中查找其他组件、配置和服务,让它找到控制器。