Beverley Talbott 13 лет назад
Родитель
Сommit
4fa4d5343b
2 измененных файлов: 186 добавлений и 0 удалений
  1. 164
    0
      README.ftl.md
  2. 22
    0
      SIDEBAR.md

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

@@ -0,0 +1,164 @@
1
+<#assign project_id="gs-rest-service">
2
+
3
+# Getting Started: Building a RESTful Web Service
4
+
5
+What you'll build
6
+-----------------
7
+
8
+This guide walks you through creating a "hello world" [RESTful web service][u-rest] with Spring. The service will accept HTTP GET requests at:
9
+
10
+    http://localhost:8080/greeting
11
+
12
+and respond with a [JSON][u-json] representation of a greeting:
13
+
14
+    {"id":1,"content":"Hello, World!"}
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
+    {"id":1,"content":"Hello, User!"}
23
+
24
+
25
+What you'll need
26
+----------------
27
+
28
+ - About 15 minutes
29
+ - <@prereq_editor_jdk_buildtools/>
30
+
31
+
32
+## <@how_to_complete_this_guide/>
33
+
34
+
35
+<a name="scratch"></a>
36
+Set up the project
37
+------------------
38
+
39
+<@build_system_intro/>
40
+
41
+<@create_directory_structure_hello/>
42
+
43
+### Create a Maven POM
44
+
45
+    <@snippet path="pom.xml" prefix="initial"/>
46
+
47
+<@bootstrap_starter_pom_disclaimer/>
48
+
49
+
50
+<a name="initial"></a>
51
+Create a resource representation class
52
+--------------------------------------
53
+
54
+Now that you've set up the project and build system, you can create your web service.
55
+
56
+Begin the process by thinking about service interactions.
57
+
58
+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:
59
+
60
+    {
61
+        "id": 1,
62
+        "content": "Hello, World!"
63
+    }
64
+
65
+The `id` field is a unique identifier for the greeting, and `content` is the textual representation of the greeting.
66
+
67
+To model the greeting representation, you create a _resource representation class_. To do this, you simply create a plain old java object with fields, constructors, and accessors for the `id` and `content` data:
68
+
69
+    <@snippet path="src/main/java/hello/Greeting.java" prefix="complete"/>
70
+
71
+> **Note:** As you'll see in steps below, Spring will use the _Jackson_ JSON library to automatically marshal instances of type `Greeting` into JSON.
72
+
73
+Next you create the resource controller that will serve these greetings.
74
+
75
+
76
+Create a resource controller
77
+------------------------------
78
+
79
+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:
80
+
81
+    <@snippet path="src/main/java/hello/GreetingController.java" prefix="complete"/>
82
+
83
+This controller is concise and simple, but there's plenty going on under the hood. Let's break it down step by step.
84
+
85
+The `@RequestMapping` annotation ensures that HTTP requests to `/greeting` are mapped to the `greeting()` method.
86
+
87
+> **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.
88
+
89
+`@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.
90
+
91
+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`.
92
+
93
+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.
94
+
95
+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.
96
+
97
+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.
98
+
99
+
100
+Make the application executable
101
+-------------------------------
102
+
103
+Although it is possible to package this service as a traditional _web application archive_ or [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. And 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.
104
+
105
+### Create a main class
106
+
107
+    <@snippet path="src/main/java/hello/Application.java" prefix="complete"/>
108
+
109
+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]_.
110
+
111
+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.
112
+
113
+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.
114
+
115
+### <@build_an_executable_jar/>
116
+
117
+
118
+Run the service
119
+---------------
120
+
121
+Run your service with `java -jar` at the command line:
122
+
123
+    java -jar target/gs-rest-service-0.1.0.jar
124
+
125
+Logging output is displayed. The service should be up and running within a few seconds.
126
+
127
+
128
+Test the service
129
+----------------
130
+
131
+Now that the service is up, visit <http://localhost:8080/greeting>, where you see:
132
+
133
+    {"id":1,"content":"Hello, World!"}
134
+
135
+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!":
136
+
137
+    {"id":2,"content":"Hello, User!"}
138
+
139
+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.
140
+
141
+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.
142
+
143
+
144
+Summary
145
+-------
146
+
147
+Congrats! You've just developed a RESTful web service with Spring. This of course is just the beginning, and there are many more features to explore and take advantage of. Be sure to check out Spring's support for [securing](TODO), [describing](TODO) [managing](TODO), [testing](TODO) and [consuming](/gs-consuming-rest) RESTful web services.
148
+
149
+
150
+[zip]: https://github.com/springframework-meta/gs-rest-service/archive/master.zip
151
+[u-rest]: /understanding/rest
152
+[u-json]: /understanding/json
153
+[u-jsp]: /understanding/jsp
154
+[jackson]: http://wiki.fasterxml.com/JacksonHome
155
+[u-war]: /understanding/war
156
+[u-tomcat]: /understanding/tomcat
157
+[u-application-context]: /understanding/application-context
158
+[`@Controller`]: http://static.springsource.org/spring/docs/current/javadoc-api/org/springframework/stereotype/Controller.html
159
+[`SpringApplication`]: http://static.springsource.org/spring-bootstrap/docs/0.5.0.BUILD-SNAPSHOT/javadoc-api/org/springframework/bootstrap/SpringApplication.html
160
+[`@EnableAutoConfiguration`]: http://static.springsource.org/spring-bootstrap/docs/0.5.0.BUILD-SNAPSHOT/javadoc-api/org/springframework/bootstrap/context/annotation/SpringApplication.html
161
+[`@Component`]: http://static.springsource.org/spring/docs/current/javadoc-api/org/springframework/stereotype/Component.html
162
+[`@ResponseBody`]: http://static.springsource.org/spring/docs/current/javadoc-api/org/springframework/web/bind/annotation/ResponseBody.html
163
+[`MappingJackson2HttpMessageConverter`]: http://static.springsource.org/spring/docs/current/javadoc-api/org/springframework/http/converter/json/MappingJackson2HttpMessageConverter.html
164
+[`DispatcherServlet`]: http://static.springsource.org/spring/docs/current/javadoc-api/org/springframework/web/servlet/DispatcherServlet.html

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

@@ -0,0 +1,22 @@
1
+
2
+Related Resources
3
+-----------------
4
+
5
+There's more to building RESTful web services than is covered here. You may want to continue your exploration of Spring and REST with the following
6
+
7
+### Getting Started guides:
8
+
9
+* Handling POST, PUT, and GET requests in REST services
10
+* Creating self-describing APIs with HATEOAS
11
+* Securing a REST service with HTTP Basic
12
+* Securing a REST service with OAuth
13
+* Consuming REST services
14
+* Testing REST services
15
+
16
+### Understanding
17
+
18
+* [Understanding REST][u-rest]
19
+* [Understanding Json][u-json]
20
+
21
+[u-rest]: /understanding/rest
22
+[u-json]: /understanding/json