Просмотр исходного кода

Regenerate README.md based on updates

Greg Turnquist 13 лет назад
Родитель
Сommit
b96db16ee1
1 измененных файлов: 328 добавлений и 0 удалений
  1. 328
    0
      README.md

+ 328
- 0
README.md Просмотреть файл

@@ -0,0 +1,328 @@
1
+
2
+# Getting Started: Building a RESTful Web Service
3
+
4
+What you'll build
5
+-----------------
6
+
7
+This guide walks you through creating a "hello world" [RESTful web service][u-rest] with Spring. The service will accept HTTP GET requests at:
8
+
9
+    http://localhost:8080/greeting
10
+
11
+and respond with a [JSON][u-json] representation of a greeting:
12
+
13
+    {"id":1,"content":"Hello, World!"}
14
+
15
+You can customize the greeting with an optional `name` parameter in the query string:
16
+
17
+    http://localhost:8080/greeting?name=User
18
+
19
+The `name` parameter value overrides the default value of "World" and is reflected in the response:
20
+
21
+    {"id":1,"content":"Hello, User!"}
22
+
23
+
24
+What you'll need
25
+----------------
26
+
27
+ - About 15 minutes
28
+ - A favorite text editor or IDE
29
+ - [JDK 6][jdk] or later
30
+ - [Maven 3.0][mvn] or later
31
+
32
+[jdk]: http://www.oracle.com/technetwork/java/javase/downloads/index.html
33
+[mvn]: http://maven.apache.org/download.cgi
34
+
35
+
36
+How to complete this guide
37
+--------------------------
38
+
39
+Like all Spring's [Getting Started guides](/getting-started), you can start from scratch and complete each step, or you can bypass basic setup steps that are already familiar to you. Either way, you end up with working code.
40
+
41
+To **start from scratch**, move on to [Set up the project](#scratch).
42
+
43
+To **skip the basics**, do the following:
44
+
45
+ - [Download][zip] and unzip the source repository for this guide, or clone it using [git](/understanding/git):
46
+`git clone https://github.com/springframework-meta/gs-rest-service.git`
47
+ - cd into `gs-rest-service/initial`
48
+ - Jump ahead to [Create a resource representation class](#initial).
49
+
50
+**When you're finished**, you can check your results against the code in `gs-rest-service/complete`.
51
+[zip]: https://github.com/springframework-meta/gs-rest-service/archive/master.zip
52
+
53
+
54
+<a name="scratch"></a>
55
+Set up the project
56
+------------------
57
+
58
+First you set up a basic build script. You can use any build system you like when building apps with Spring, but the code you need to work with [Maven](https://maven.apache.org) and [Gradle](http://gradle.org) is included here. If you're not familiar with either, refer to [Building Java Projects with Maven](../gs-maven/README.md) or [Building Java Projects with Gradle](../gs-gradle/README.md).
59
+
60
+### Create the directory structure
61
+
62
+In a project directory of your choosing, create the following subdirectory structure; for example, with `mkdir -p src/main/java/hello` on *nix systems:
63
+
64
+    └── src
65
+        └── main
66
+            └── java
67
+                └── hello
68
+
69
+### Create a Maven POM
70
+
71
+`pom.xml`
72
+```xml
73
+<?xml version="1.0" encoding="UTF-8"?>
74
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
75
+    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
76
+    <modelVersion>4.0.0</modelVersion>
77
+
78
+    <groupId>org.springframework</groupId>
79
+    <artifactId>gs-rest-service</artifactId>
80
+    <version>0.1.0</version>
81
+
82
+    <parent>
83
+        <groupId>org.springframework.bootstrap</groupId>
84
+        <artifactId>spring-bootstrap-starters</artifactId>
85
+        <version>0.5.0.BUILD-SNAPSHOT</version>
86
+    </parent>
87
+
88
+    <dependencies>
89
+        <dependency>
90
+            <groupId>org.springframework.bootstrap</groupId>
91
+            <artifactId>spring-bootstrap-web-starter</artifactId>
92
+        </dependency>
93
+        <dependency>
94
+            <groupId>com.fasterxml.jackson.core</groupId>
95
+            <artifactId>jackson-databind</artifactId>
96
+        </dependency>
97
+    </dependencies>
98
+
99
+    <!-- TODO: remove once bootstrap goes GA -->
100
+    <repositories>
101
+        <repository>
102
+            <id>spring-snapshots</id>
103
+            <url>http://repo.springsource.org/snapshot</url>
104
+            <snapshots><enabled>true</enabled></snapshots>
105
+        </repository>
106
+    </repositories>
107
+    <pluginRepositories>
108
+        <pluginRepository>
109
+            <id>spring-snapshots</id>
110
+            <url>http://repo.springsource.org/snapshot</url>
111
+            <snapshots><enabled>true</enabled></snapshots>
112
+        </pluginRepository>
113
+    </pluginRepositories>
114
+</project>
115
+```
116
+
117
+TODO: mention that we're using Spring Bootstrap's [_starter POMs_](../gs-bootstrap-starter) here.
118
+
119
+Note to experienced Maven users who are unaccustomed to using an external parent project: you can take it out later, it's just there to reduce the amount of code you have to write to get started.
120
+
121
+
122
+<a name="initial"></a>
123
+Create a resource representation class
124
+--------------------------------------
125
+
126
+Now that you've set up the project and build system, you can create your web service.
127
+
128
+Begin the process by thinking about service interactions.
129
+
130
+The service will handle `GET` requests for `/greeting`, optionally with a `name` parameter in the query string. The `GET` request should return a `200 OK` response with JSON in the body that represents a greeting. It should look something like this:
131
+
132
+    {
133
+        "id": 1,
134
+        "content": "Hello, World!"
135
+    }
136
+
137
+The `id` field is a unique identifier for the greeting, and `content` is the textual representation of the greeting.
138
+
139
+To model the greeting representation, you create a resource representation class. Provide a plain old java object with fields, constructors, and accessors for the `id` and `content` data:
140
+
141
+`src/main/java/hello/Greeting.java`
142
+```java
143
+package hello;
144
+
145
+public class Greeting {
146
+
147
+    private final long id;
148
+    private final String content;
149
+
150
+    public Greeting(long id, String content) {
151
+        this.id = id;
152
+        this.content = content;
153
+    }
154
+
155
+    public long getId() {
156
+        return id;
157
+    }
158
+
159
+    public String getContent() {
160
+        return content;
161
+    }
162
+}
163
+```
164
+
165
+> **Note:** As you see in steps below, Spring uses the [Jackson JSON][jackson] library to automatically marshal instances of type `Greeting` into JSON.
166
+
167
+Next you create the resource controller that will serve these greetings.
168
+
169
+
170
+Create a resource controller
171
+------------------------------
172
+
173
+In Spring's approach to building RESTful web services, HTTP requests are handled by a controller. These components are easily identified by the [`@Controller`][] annotation, and the `GreetingController` below handles `GET` requests for `/greeting` by returning a new instance of the `Greeting` class:
174
+
175
+`src/main/java/hello/GreetingController.java`
176
+```java
177
+package hello;
178
+
179
+import java.util.concurrent.atomic.AtomicLong;
180
+import org.springframework.stereotype.Controller;
181
+import org.springframework.web.bind.annotation.RequestMapping;
182
+import org.springframework.web.bind.annotation.RequestParam;
183
+import org.springframework.web.bind.annotation.ResponseBody;
184
+
185
+@Controller
186
+public class GreetingController {
187
+
188
+    private static final String template = "Hello, %s!";
189
+    private final AtomicLong counter = new AtomicLong();
190
+
191
+    @RequestMapping("/greeting")
192
+    public @ResponseBody Greeting greeting(
193
+            @RequestParam(value="name", required=false, defaultValue="World") String name) {
194
+        return new Greeting(counter.incrementAndGet(),
195
+                            String.format(template, name));
196
+    }
197
+}
198
+```
199
+
200
+This controller is concise and simple, but there's plenty going on under the hood. Let's break it down step by step.
201
+
202
+The `@RequestMapping` annotation ensures that HTTP requests to `/greeting` are mapped to the `greeting()` method.
203
+
204
+> **Note:** The above example does not specify `GET` vs. `PUT`, `POST`, and so forth, because `@RequestMapping` maps all HTTP operations by default. Use `@RequestMapping(method=GET)` to narrow this mapping.
205
+
206
+`@RequestParam` binds the value of the query string parameter `name` into the `name` parameter of the `greeting()` method. This query string parameter is not `required`; if it is absent in the request, the `defaultValue` of "World" is used.
207
+
208
+The implementation of the method body creates and returns a new `Greeting` object with `id` and `content` attributes based on the next value from the `counter`, and formats the given `name` by using the greeting `template`.
209
+
210
+A key difference between a traditional MVC controller and the RESTful web service controller above is the way that the HTTP response body is created. Rather than relying on a view technology (such as [JSP][u-jsp]) to perform server-side rendering of the greeting data to HTML, this RESTful web service controller simply populates and returns a `Greeting` object. The object data will be written directly to the HTTP response as JSON.
211
+
212
+To accomplish this, the [`@ResponseBody`][] annotation on the `greeting()` method tells Spring MVC that it does not need to render the greeting object through a server-side view layer, but that instead that the greeting object returned _is_ the response body, and should be written out directly.
213
+
214
+The `Greeting` object must be converted to JSON. Thanks to Spring's HTTP message converter support, you don't need to do this conversion manually. Because [Jackson 2][jackson] is on the classpath, Spring's [`MappingJackson2HttpMessageConverter`][] is automatically chosen to convert the `Greeting` instance to JSON.
215
+
216
+
217
+Make the application executable
218
+-------------------------------
219
+
220
+Although it is possible to package this service as a traditional [WAR][u-war] file for deployment to an external application server, the simpler approach demonstrated below creates a standalone application. You package everything in a single, executable JAR file, driven by a good old Java `main()` method. Along the way, you use Spring's support for embedding the [Tomcat][u-tomcat] servlet container as the HTTP runtime, instead of deploying to an external instance.
221
+
222
+### Create an Application class
223
+
224
+`src/main/java/hello/Application.java`
225
+```java
226
+package hello;
227
+
228
+import org.springframework.bootstrap.SpringApplication;
229
+import org.springframework.bootstrap.context.annotation.EnableAutoConfiguration;
230
+import org.springframework.context.annotation.ComponentScan;
231
+
232
+@ComponentScan
233
+@EnableAutoConfiguration
234
+public class Application {
235
+
236
+    public static void main(String[] args) {
237
+        SpringApplication.run(Application.class, args);
238
+    }
239
+}
240
+```
241
+
242
+The `main()` method defers to the [`SpringApplication`][] helper class, providing `Application.class` as an argument to its `run()` method. This tells Spring to read the annotation metadata from `Application` and to manage it as a component in the [Spring application context][u-application-context].
243
+
244
+The `@ComponentScan` annotation tells Spring to search recursively through the `hello` package and its children for classes marked directly or indirectly with Spring's [`@Component`][] annotation. This directive ensures that Spring finds and registers the `GreetingController`, because it is marked with `@Controller`, which in turn is a kind of `@Component` annotation.
245
+
246
+The [`@EnableAutoConfiguration`][] annotation switches on reasonable default behaviors based on the content of your classpath. For example, because the application depends on the embeddable version of Tomcat (tomcat-embed-core.jar), a Tomcat server is set up and configured with reasonable defaults on your behalf. And because the application also depends on Spring MVC (spring-webmvc.jar), a Spring MVC [`DispatcherServlet`][] is configured and registered for you — no `web.xml` necessary! Auto-configuration is a powerful, flexible mechanism. See the [API documentation][`@EnableAutoConfiguration`] for further details.
247
+
248
+### Build an executable JAR
249
+-----------------------
250
+
251
+Now that your `Application` class is ready, you simply instruct the build system to create a single, executable jar containing everything. This makes it easy to ship, version, and deploy the service as an application throughout the development lifecycle, across different environments, and so forth.
252
+
253
+Add the following configuration to your existing Maven POM:
254
+
255
+`pom.xml`
256
+```xml
257
+    <properties>
258
+        <start-class>hello.Application</start-class>
259
+    </properties>
260
+
261
+    <build>
262
+        <plugins>
263
+            <plugin>
264
+                <groupId>org.apache.maven.plugins</groupId>
265
+                <artifactId>maven-shade-plugin</artifactId>
266
+            </plugin>
267
+        </plugins>
268
+    </build>
269
+```
270
+
271
+The `start-class` property tells Maven to create a `META-INF/MANIFEST.MF` file with a `Main-Class: hello.Application` entry. This entry enables you to run the jar with `java -jar`.
272
+
273
+The [Maven Shade plugin][maven-shade-plugin] extracts classes from all jars on the classpath and builds a single "über-jar", which makes it more convenient to execute and transport your service.
274
+
275
+Now run the following to produce a single executable JAR file containing all necessary dependency classes and resources:
276
+
277
+    mvn package
278
+
279
+[maven-shade-plugin]: https://maven.apache.org/plugins/maven-shade-plugin
280
+
281
+Run the service
282
+-------------------
283
+Run your service with `java -jar` at the command line:
284
+
285
+    java -jar target/gs-rest-service-0.1.0.jar
286
+
287
+
288
+
289
+Logging output is displayed. The service should be up and running within a few seconds.
290
+
291
+
292
+Test the service
293
+----------------
294
+
295
+Now that the service is up, visit <http://localhost:8080/greeting>, where you see:
296
+
297
+    {"id":1,"content":"Hello, World!"}
298
+
299
+Provide a `name` query string parameter with <http://localhost:8080/greeting?name=User>. Notice how the value of the `content` attribute changes from "Hello, World!" to "Hello User!":
300
+
301
+    {"id":2,"content":"Hello, User!"}
302
+
303
+This change demonstrates that the `@RequestParam` arrangement in `GreetingController` is working as expected. The `name` parameter has been given a default value of "World", but can always be explicitly overridden through the query string.
304
+
305
+Notice also how the `id` attribute has changed from `1` to `2`. This proves that you are working against the same `GreetingController` instance across multiple requests, and that its `counter` field is being incremented on each call as expected.
306
+
307
+
308
+Summary
309
+-------
310
+
311
+Congratulations! You've just developed a RESTful web service with Spring. 
312
+
313
+
314
+
315
+[u-rest]: /understanding/rest
316
+[u-json]: /understanding/json
317
+[u-jsp]: /understanding/jsp
318
+[jackson]: http://wiki.fasterxml.com/JacksonHome
319
+[u-war]: /understanding/war
320
+[u-tomcat]: /understanding/tomcat
321
+[u-application-context]: /understanding/application-context
322
+[`@Controller`]: http://static.springsource.org/spring/docs/current/javadoc-api/org/springframework/stereotype/Controller.html
323
+[`SpringApplication`]: http://static.springsource.org/spring-bootstrap/docs/0.5.0.BUILD-SNAPSHOT/javadoc-api/org/springframework/bootstrap/SpringApplication.html
324
+[`@EnableAutoConfiguration`]: http://static.springsource.org/spring-bootstrap/docs/0.5.0.BUILD-SNAPSHOT/javadoc-api/org/springframework/bootstrap/context/annotation/SpringApplication.html
325
+[`@Component`]: http://static.springsource.org/spring/docs/current/javadoc-api/org/springframework/stereotype/Component.html
326
+[`@ResponseBody`]: http://static.springsource.org/spring/docs/current/javadoc-api/org/springframework/web/bind/annotation/ResponseBody.html
327
+[`MappingJackson2HttpMessageConverter`]: http://static.springsource.org/spring/docs/current/javadoc-api/org/springframework/http/converter/json/MappingJackson2HttpMessageConverter.html
328
+[`DispatcherServlet`]: http://static.springsource.org/spring/docs/current/javadoc-api/org/springframework/web/servlet/DispatcherServlet.html