spring guide 翻译[1]

(随性)翻译spring官网上的文章

使用spring搭建一个 RESTful web服务

我们最后构建出的项目可以接收一个类似于


http://localhost:8080/greeting
HTTP GET 请求 我们的应用会返回一个 JSON 数据给它

{"id":1,"content":"Hello, World!"}
你可以添加参数来定制一个 HTTP 请求 像

http://localhost:8080/greeting?name=User
这样 这个name参数值会覆盖掉应用默认返回的 World

{"id":1,"content":"Hello, User!"}
首先借助spring构建工具,新建一个项目。 先理清这个应用的思路 我们接收一个 get 请求 ,这个请求有一个叫做 name 的可选参数 get 请求会返回一个 200 OK 和 JSON 数据

{
    "id": 1,
    "content": "Hello, World!"
}
这个 id 字段 是请求的 唯一标志, content字段 是返回的文字内容 所以我们需要新建一个 POJO(Plain old java object)来返回它 这个pojo是下面这个样子

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;
    }
}
spring 会使用 jackson json库 自动将 Greeting对象转变成 json数据 接下面我们要创建 controller 来处理请求 spring使用 @RestController 注解 controller

import java.util.concurrent.atomic.AtomicLong;
import org.springframework.web.bind.annotation.RequestMapping;
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();

    @RequestMapping("/greeting")
    public Greeting greeting(@RequestParam(value="name", defaultValue="World") String name) {
        return new Greeting(counter.incrementAndGet(),
                            String.format(template, name));
    }
}
这个 controller代码直观且简单,但是它简约而不简单 一步步来看它 @RequestMapping 注解 确保 /greeting 请求 会被 greeting方法处理 @RequestMapping 注解会匹配所有的 HTTP请求类型,不管你是 GET 还是 PUT 还是 POST 当然你也可以使用 @RequestMapping(method=GET) 来指定处理 的HTTP请求类型 @RequestParam 注解将 name参数的值 绑定给name字段 name参数是可选的,如果它缺失,defaultValue 'world'就会被使用 和 传统的 MVC controller 不同的是, 我们的 RESTful web应用不会结果展示成 html 而是返回一个 Greeting 对象, 这个对象的数据会被直接以JSON的形式返回 @RestController 是spring 4推出的注解, 是 @Controller 和 @ResponseBody 两个注解的结合使用 你不需要手动 将 Greeting对象 转变成json 因为spring的MappingJackson2HttpMessageConverter已经自动完成这件事了 接下来 让我们运行项目 在项目自动生成的Application中 我们看到它被 SpringBootApplication注解 @SpringBootApplication注解 是一个便利的注解 包含以下 4种注解的功能 @Configuration @EnableAutoConfiguration 告诉 spring boot 加载各种配置 @EnableWebMvc 将我们的应用标记成一个 网络应用 这样应用的一些关键内容例如 DispatcherServlet 才会被激活 @ComponentScan告诉 spring寻找其他"部分"(我们自己编写的代码) 到目前为止 我们还没有配置过一行 xml 点击 run 运行项目, 访问 http://localhost:8080/greeting, 你会看到

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

访问 http://localhost:8080/greeting?name=User.


{“id”:2,”content”:”Hello, User!”}

你会发现我们的 id 值 增加了,说明这两次请求访问的是同一个
GreetingController(–!)