|
|
@@ -1,354 +0,0 @@
|
|
1
|
|
-This guide walks you through the process of creating a "hello world" [RESTful web service][u-rest] with Spring.
|
|
2
|
|
-
|
|
3
|
|
-What you'll build
|
|
4
|
|
------------------
|
|
5
|
|
-
|
|
6
|
|
-You'll build a service that will accept HTTP GET requests at:
|
|
7
|
|
-
|
|
8
|
|
- http://localhost:8080/greeting
|
|
9
|
|
-
|
|
10
|
|
-and respond with a [JSON][u-json] representation of a greeting:
|
|
11
|
|
-
|
|
12
|
|
-```json
|
|
13
|
|
-{"id":1,"content":"Hello, World!"}
|
|
14
|
|
-```
|
|
15
|
|
-
|
|
16
|
|
-You can customize the greeting with an optional `name` parameter in the query string:
|
|
17
|
|
-
|
|
18
|
|
- http://localhost:8080/greeting?name=User
|
|
19
|
|
-
|
|
20
|
|
-The `name` parameter value overrides the default value of "World" and is reflected in the response:
|
|
21
|
|
-
|
|
22
|
|
-```json
|
|
23
|
|
-{"id":1,"content":"Hello, User!"}
|
|
24
|
|
-```
|
|
25
|
|
-
|
|
26
|
|
-
|
|
27
|
|
-What you'll need
|
|
28
|
|
-----------------
|
|
29
|
|
-
|
|
30
|
|
- - About 15 minutes
|
|
31
|
|
- - A favorite text editor or IDE
|
|
32
|
|
- - [JDK 6][jdk] or later
|
|
33
|
|
- - [Gradle 1.8+][gradle] or [Maven 3.0+][mvn]
|
|
34
|
|
- - You can also import the code from this guide as well as view the web page directly into [Spring Tool Suite (STS)][gs-sts] and work your way through it from there.
|
|
35
|
|
-
|
|
36
|
|
-[jdk]: http://www.oracle.com/technetwork/java/javase/downloads/index.html
|
|
37
|
|
-[gradle]: http://www.gradle.org/
|
|
38
|
|
-[mvn]: http://maven.apache.org/download.cgi
|
|
39
|
|
-[gs-sts]: /guides/gs/sts
|
|
40
|
|
-
|
|
41
|
|
-
|
|
42
|
|
-How to complete this guide
|
|
43
|
|
---------------------------
|
|
44
|
|
-
|
|
45
|
|
-Like all Spring's [Getting Started guides](/guides/gs), 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.
|
|
46
|
|
-
|
|
47
|
|
-To **start from scratch**, move on to [Set up the project](#scratch).
|
|
48
|
|
-
|
|
49
|
|
-To **skip the basics**, do the following:
|
|
50
|
|
-
|
|
51
|
|
- - [Download][zip] and unzip the source repository for this guide, or clone it using [Git][u-git]:
|
|
52
|
|
-`git clone https://github.com/spring-guides/gs-rest-service.git`
|
|
53
|
|
- - cd into `gs-rest-service/initial`.
|
|
54
|
|
- - Jump ahead to [Create a resource representation class](#initial).
|
|
55
|
|
-
|
|
56
|
|
-**When you're finished**, you can check your results against the code in `gs-rest-service/complete`.
|
|
57
|
|
-[zip]: https://github.com/spring-guides/gs-rest-service/archive/master.zip
|
|
58
|
|
-[u-git]: /understanding/Git
|
|
59
|
|
-
|
|
60
|
|
-
|
|
61
|
|
-<a name="scratch"></a>
|
|
62
|
|
-Set up the project
|
|
63
|
|
-------------------
|
|
64
|
|
-
|
|
65
|
|
-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 [Gradle](http://gradle.org) and [Maven](https://maven.apache.org) is included here. If you're not familiar with either, refer to [Building Java Projects with Gradle](/guides/gs/gradle/) or [Building Java Projects with Maven](/guides/gs/maven).
|
|
66
|
|
-
|
|
67
|
|
-### Create the directory structure
|
|
68
|
|
-
|
|
69
|
|
-In a project directory of your choosing, create the following subdirectory structure; for example, with `mkdir -p src/main/java/hello` on *nix systems:
|
|
70
|
|
-
|
|
71
|
|
- └── src
|
|
72
|
|
- └── main
|
|
73
|
|
- └── java
|
|
74
|
|
- └── hello
|
|
75
|
|
-
|
|
76
|
|
-
|
|
77
|
|
-### Create a Gradle build file
|
|
78
|
|
-Below is the [initial Gradle build file](https://github.com/spring-guides/gs-rest-service/blob/master/initial/build.gradle). But you can also use Maven. The pom.xml file is included [right here](https://github.com/spring-guides/gs-rest-service/blob/master/initial/pom.xml). If you are using [Spring Tool Suite (STS)][gs-sts], you can import the guide directly.
|
|
79
|
|
-
|
|
80
|
|
-`build.gradle`
|
|
81
|
|
-```gradle
|
|
82
|
|
-buildscript {
|
|
83
|
|
- repositories {
|
|
84
|
|
- maven { url "http://repo.spring.io/libs-snapshot" }
|
|
85
|
|
- mavenLocal()
|
|
86
|
|
- }
|
|
87
|
|
-}
|
|
88
|
|
-
|
|
89
|
|
-apply plugin: 'java'
|
|
90
|
|
-apply plugin: 'eclipse'
|
|
91
|
|
-apply plugin: 'idea'
|
|
92
|
|
-
|
|
93
|
|
-jar {
|
|
94
|
|
- baseName = 'gs-rest-service'
|
|
95
|
|
- version = '0.1.0'
|
|
96
|
|
-}
|
|
97
|
|
-
|
|
98
|
|
-repositories {
|
|
99
|
|
- mavenCentral()
|
|
100
|
|
- maven { url "http://repo.spring.io/libs-snapshot" }
|
|
101
|
|
-}
|
|
102
|
|
-
|
|
103
|
|
-dependencies {
|
|
104
|
|
- compile("org.springframework.boot:spring-boot-starter-web:0.5.0.M6")
|
|
105
|
|
- compile("com.fasterxml.jackson.core:jackson-databind")
|
|
106
|
|
- testCompile("junit:junit:4.11")
|
|
107
|
|
-}
|
|
108
|
|
-
|
|
109
|
|
-task wrapper(type: Wrapper) {
|
|
110
|
|
- gradleVersion = '1.8'
|
|
111
|
|
-}
|
|
112
|
|
-```
|
|
113
|
|
-
|
|
114
|
|
-[gs-sts]: /guides/gs/sts
|
|
115
|
|
-
|
|
116
|
|
-> **Note:** This guide is using [Spring Boot](/guides/gs/spring-boot/).
|
|
117
|
|
-
|
|
118
|
|
-
|
|
119
|
|
-<a name="initial"></a>
|
|
120
|
|
-Create a resource representation class
|
|
121
|
|
---------------------------------------
|
|
122
|
|
-
|
|
123
|
|
-Now that you've set up the project and build system, you can create your web service.
|
|
124
|
|
-
|
|
125
|
|
-Begin the process by thinking about service interactions.
|
|
126
|
|
-
|
|
127
|
|
-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:
|
|
128
|
|
-
|
|
129
|
|
-```json
|
|
130
|
|
-{
|
|
131
|
|
- "id": 1,
|
|
132
|
|
- "content": "Hello, World!"
|
|
133
|
|
-}
|
|
134
|
|
-```
|
|
135
|
|
-
|
|
136
|
|
-The `id` field is a unique identifier for the greeting, and `content` is the textual representation of the greeting.
|
|
137
|
|
-
|
|
138
|
|
-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:
|
|
139
|
|
-
|
|
140
|
|
-`src/main/java/hello/Greeting.java`
|
|
141
|
|
-```java
|
|
142
|
|
-package hello;
|
|
143
|
|
-
|
|
144
|
|
-public class Greeting {
|
|
145
|
|
-
|
|
146
|
|
- private final long id;
|
|
147
|
|
- private final String content;
|
|
148
|
|
-
|
|
149
|
|
- public Greeting(long id, String content) {
|
|
150
|
|
- this.id = id;
|
|
151
|
|
- this.content = content;
|
|
152
|
|
- }
|
|
153
|
|
-
|
|
154
|
|
- public long getId() {
|
|
155
|
|
- return id;
|
|
156
|
|
- }
|
|
157
|
|
-
|
|
158
|
|
- public String getContent() {
|
|
159
|
|
- return content;
|
|
160
|
|
- }
|
|
161
|
|
-}
|
|
162
|
|
-```
|
|
163
|
|
-
|
|
164
|
|
-> **Note:** As you see in steps below, Spring uses the [Jackson JSON][jackson] library to automatically marshal instances of type `Greeting` into JSON.
|
|
165
|
|
-
|
|
166
|
|
-Next you create the resource controller that will serve these greetings.
|
|
167
|
|
-
|
|
168
|
|
-
|
|
169
|
|
-Create a resource controller
|
|
170
|
|
-------------------------------
|
|
171
|
|
-
|
|
172
|
|
-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:
|
|
173
|
|
-
|
|
174
|
|
-`src/main/java/hello/GreetingController.java`
|
|
175
|
|
-```java
|
|
176
|
|
-package hello;
|
|
177
|
|
-
|
|
178
|
|
-import java.util.concurrent.atomic.AtomicLong;
|
|
179
|
|
-import org.springframework.stereotype.Controller;
|
|
180
|
|
-import org.springframework.web.bind.annotation.RequestMapping;
|
|
181
|
|
-import org.springframework.web.bind.annotation.RequestParam;
|
|
182
|
|
-import org.springframework.web.bind.annotation.ResponseBody;
|
|
183
|
|
-
|
|
184
|
|
-@Controller
|
|
185
|
|
-public class GreetingController {
|
|
186
|
|
-
|
|
187
|
|
- private static final String template = "Hello, %s!";
|
|
188
|
|
- private final AtomicLong counter = new AtomicLong();
|
|
189
|
|
-
|
|
190
|
|
- @RequestMapping("/greeting")
|
|
191
|
|
- public @ResponseBody Greeting greeting(
|
|
192
|
|
- @RequestParam(value="name", required=false, defaultValue="World") String name) {
|
|
193
|
|
- return new Greeting(counter.incrementAndGet(),
|
|
194
|
|
- String.format(template, name));
|
|
195
|
|
- }
|
|
196
|
|
-}
|
|
197
|
|
-```
|
|
198
|
|
-
|
|
199
|
|
-This controller is concise and simple, but there's plenty going on under the hood. Let's break it down step by step.
|
|
200
|
|
-
|
|
201
|
|
-The `@RequestMapping` annotation ensures that HTTP requests to `/greeting` are mapped to the `greeting()` method.
|
|
202
|
|
-
|
|
203
|
|
-> **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.
|
|
204
|
|
-
|
|
205
|
|
-`@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.
|
|
206
|
|
-
|
|
207
|
|
-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`.
|
|
208
|
|
-
|
|
209
|
|
-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][u-view-templates] 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.
|
|
210
|
|
-
|
|
211
|
|
-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.
|
|
212
|
|
-
|
|
213
|
|
-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.
|
|
214
|
|
-
|
|
215
|
|
-
|
|
216
|
|
-Make the application executable
|
|
217
|
|
--------------------------------
|
|
218
|
|
-
|
|
219
|
|
-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.
|
|
220
|
|
-
|
|
221
|
|
-### Create an Application class
|
|
222
|
|
-
|
|
223
|
|
-`src/main/java/hello/Application.java`
|
|
224
|
|
-```java
|
|
225
|
|
-package hello;
|
|
226
|
|
-
|
|
227
|
|
-import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
|
|
228
|
|
-import org.springframework.boot.SpringApplication;
|
|
229
|
|
-import org.springframework.context.annotation.ComponentScan;
|
|
230
|
|
-
|
|
231
|
|
-@ComponentScan
|
|
232
|
|
-@EnableAutoConfiguration
|
|
233
|
|
-public class Application {
|
|
234
|
|
-
|
|
235
|
|
- public static void main(String[] args) {
|
|
236
|
|
- SpringApplication.run(Application.class, args);
|
|
237
|
|
- }
|
|
238
|
|
-}
|
|
239
|
|
-```
|
|
240
|
|
-
|
|
241
|
|
-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].
|
|
242
|
|
-
|
|
243
|
|
-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.
|
|
244
|
|
-
|
|
245
|
|
-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.
|
|
246
|
|
-
|
|
247
|
|
-### Build an executable JAR
|
|
248
|
|
-
|
|
249
|
|
-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.
|
|
250
|
|
-
|
|
251
|
|
-Below are the Gradle steps, but if you are using Maven, you can find the updated pom.xml [right here](https://github.com/spring-guides/gs-rest-service/blob/master/complete/pom.xml) and build it by typing `mvn clean package`.
|
|
252
|
|
-
|
|
253
|
|
-Update your Gradle `build.gradle` file's `buildscript` section, so that it looks like this:
|
|
254
|
|
-
|
|
255
|
|
-```groovy
|
|
256
|
|
-buildscript {
|
|
257
|
|
- repositories {
|
|
258
|
|
- maven { url "http://repo.spring.io/libs-snapshot" }
|
|
259
|
|
- mavenLocal()
|
|
260
|
|
- }
|
|
261
|
|
- dependencies {
|
|
262
|
|
- classpath("org.springframework.boot:spring-boot-gradle-plugin:0.5.0.M6")
|
|
263
|
|
- }
|
|
264
|
|
-}
|
|
265
|
|
-```
|
|
266
|
|
-
|
|
267
|
|
-Further down inside `build.gradle`, add the following to the list of applied plugins:
|
|
268
|
|
-
|
|
269
|
|
-```groovy
|
|
270
|
|
-apply plugin: 'spring-boot'
|
|
271
|
|
-```
|
|
272
|
|
-You can see the final version of `build.gradle` [right here]((https://github.com/spring-guides/gs-rest-service/blob/master/complete/build.gradle).
|
|
273
|
|
-
|
|
274
|
|
-The [Spring Boot gradle plugin][spring-boot-gradle-plugin] collects all the jars on the classpath and builds a single "über-jar", which makes it more convenient to execute and transport your service.
|
|
275
|
|
-It also searches for the `public static void main()` method to flag as a runnable class.
|
|
276
|
|
-
|
|
277
|
|
-Now run the following command to produce a single executable JAR file containing all necessary dependency classes and resources:
|
|
278
|
|
-
|
|
279
|
|
-```sh
|
|
280
|
|
-$ ./gradlew build
|
|
281
|
|
-```
|
|
282
|
|
-
|
|
283
|
|
-If you are using Gradle, you can run the JAR by typing:
|
|
284
|
|
-
|
|
285
|
|
-```sh
|
|
286
|
|
-$ java -jar build/libs/gs-rest-service-0.1.0.jar
|
|
287
|
|
-```
|
|
288
|
|
-
|
|
289
|
|
-If you are using Maven, you can run the JAR by typing:
|
|
290
|
|
-
|
|
291
|
|
-```sh
|
|
292
|
|
-$ java -jar target/gs-rest-service-0.1.0.jar
|
|
293
|
|
-```
|
|
294
|
|
-
|
|
295
|
|
-[spring-boot-gradle-plugin]: https://github.com/spring-projects/spring-boot/tree/master/spring-boot-tools/spring-boot-gradle-plugin
|
|
296
|
|
-
|
|
297
|
|
-> **Note:** The procedure above will create a runnable JAR. You can also opt to [build a classic WAR file](/guides/gs/convert-jar-to-war/) instead.
|
|
298
|
|
-
|
|
299
|
|
-Run the service
|
|
300
|
|
--------------------
|
|
301
|
|
-If you are using Gradle, you can run your service at the command line this way:
|
|
302
|
|
-
|
|
303
|
|
-```sh
|
|
304
|
|
-$ ./gradlew clean build && java -jar build/libs/gs-rest-service-0.1.0.jar
|
|
305
|
|
-```
|
|
306
|
|
-
|
|
307
|
|
-> **Note:** If you are using Maven, you can run your service by typing `mvn clean package && java -jar target/gs-rest-service-0.1.0.jar`.
|
|
308
|
|
-
|
|
309
|
|
-
|
|
310
|
|
-Logging output is displayed. The service should be up and running within a few seconds.
|
|
311
|
|
-
|
|
312
|
|
-
|
|
313
|
|
-Test the service
|
|
314
|
|
-----------------
|
|
315
|
|
-
|
|
316
|
|
-Now that the service is up, visit <http://localhost:8080/greeting>, where you see:
|
|
317
|
|
-
|
|
318
|
|
-```json
|
|
319
|
|
-{"id":1,"content":"Hello, World!"}
|
|
320
|
|
-```
|
|
321
|
|
-
|
|
322
|
|
-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!":
|
|
323
|
|
-
|
|
324
|
|
-```json
|
|
325
|
|
-{"id":2,"content":"Hello, User!"}
|
|
326
|
|
-```
|
|
327
|
|
-
|
|
328
|
|
-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.
|
|
329
|
|
-
|
|
330
|
|
-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.
|
|
331
|
|
-
|
|
332
|
|
-
|
|
333
|
|
-Summary
|
|
334
|
|
--------
|
|
335
|
|
-
|
|
336
|
|
-Congratulations! You've just developed a RESTful web service with Spring.
|
|
337
|
|
-
|
|
338
|
|
-
|
|
339
|
|
-
|
|
340
|
|
-[u-rest]: /understanding/REST
|
|
341
|
|
-[u-json]: /understanding/JSON
|
|
342
|
|
-[u-view-templates]: /understanding/view-templates
|
|
343
|
|
-[jackson]: http://wiki.fasterxml.com/JacksonHome
|
|
344
|
|
-[u-war]: /understanding/WAR
|
|
345
|
|
-[u-tomcat]: /understanding/Tomcat
|
|
346
|
|
-[u-application-context]: /understanding/application-context
|
|
347
|
|
-[`@Controller`]: http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/stereotype/Controller.html
|
|
348
|
|
-[`SpringApplication`]: http://docs.spring.io/spring-boot/docs/0.5.0.M3/api/org/springframework/boot/SpringApplication.html
|
|
349
|
|
-[`@EnableAutoConfiguration`]: http://docs.spring.io/spring-boot/docs/0.5.0.M3/api/org/springframework/boot/autoconfigure/EnableAutoConfiguration.html
|
|
350
|
|
-[`@Component`]: http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/stereotype/Component.html
|
|
351
|
|
-[`@ResponseBody`]: http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/bind/annotation/ResponseBody.html
|
|
352
|
|
-[`MappingJackson2HttpMessageConverter`]: http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/http/converter/json/MappingJackson2HttpMessageConverter.html
|
|
353
|
|
-[`DispatcherServlet`]: http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/servlet/DispatcherServlet.html
|
|
354
|
|
-
|