Pārlūkot izejas kodu

Generate README.md files from README.src.md

Chris Beams 13 gadus atpakaļ
vecāks
revīzija
7cd24ea8b6
2 mainītis faili ar 338 papildinājumiem un 12 dzēšanām
  1. 175
    12
      README.md
  2. 163
    0
      README.src.md

+ 175
- 12
README.md Parādīt failu

@@ -24,26 +24,98 @@ What you'll need
24 24
 ----------------
25 25
 
26 26
  - About 15 minutes
27
- - {!include#prereq-editor-jdk-buildtools}
27
+ - A favorite text editor or IDE
28
+ - [JDK 6][jdk] or better
29
+ - [Maven 3.0][mvn] or later
28 30
 
29
-## {!include#how-to-complete-this-guide}
31
+[jdk]: http://www.oracle.com/technetwork/java/javase/downloads/index.html
32
+[mvn]: http://maven.apache.org/download.cgi
33
+
34
+How to complete this guide
35
+--------------------------
36
+
37
+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.
38
+
39
+To **start from scratch**, move on to [Set up the project](#scratch).
40
+
41
+To **skip the basics**, do the following:
42
+
43
+ - [Download][zip] and unzip the source repository for this guide, or clone it using [git](/understanding/git):
44
+`git clone https://github.com/springframework-meta/{@project-name}.git`
45
+ - cd into `{@project-name}/initial`
46
+ - Jump ahead to [Create a resource representation class](#initial).
47
+
48
+**When you're finished**, you can check your results against the code in `{@project-name}/complete`.
30 49
 
31 50
 
32 51
 <a name="scratch"></a>
33 52
 Set up the project
34 53
 ------------------
35 54
 
36
-{!include#build-system-intro}
55
+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 our [Getting Started with Maven](../gs-maven/README.md) or [Getting Started with Gradle](../gs-gradle/README.md) guides.
37 56
 
38
-{!include#create-directory-structure-hello}
57
+### Create the directory structure
39 58
 
40
-### Create a Maven POM
59
+In a project directory of your choosing, create the following subdirectory structure; for example, with `mkdir -p src/main/java/hello` on *nix systems:
41 60
 
42
-{!include#maven-project-setup-options}
61
+    └── src
62
+        └── main
63
+            └── java
64
+                └── hello
43 65
 
44
-    {!include:initial/pom.xml}
66
+### Create a Maven POM
45 67
 
46
-{!include#bootstrap-starter-pom-disclaimer}
68
+> **ERROR:** Section 'maven-project-setup-options' not found
69
+
70
+`pom.xml`
71
+```xml
72
+<?xml version="1.0" encoding="UTF-8"?>
73
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
74
+    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
75
+    <modelVersion>4.0.0</modelVersion>
76
+
77
+    <groupId>org.springframework</groupId>
78
+    <artifactId>gs-rest-service</artifactId>
79
+    <version>0.1.0</version>
80
+
81
+    <parent>
82
+        <groupId>org.springframework.bootstrap</groupId>
83
+        <artifactId>spring-bootstrap-starters</artifactId>
84
+        <version>0.5.0.BUILD-SNAPSHOT</version>
85
+    </parent>
86
+
87
+    <dependencies>
88
+        <dependency>
89
+            <groupId>org.springframework.bootstrap</groupId>
90
+            <artifactId>spring-bootstrap-web-starter</artifactId>
91
+        </dependency>
92
+        <dependency>
93
+            <groupId>com.fasterxml.jackson.core</groupId>
94
+            <artifactId>jackson-databind</artifactId>
95
+        </dependency>
96
+    </dependencies>
97
+
98
+    <!-- TODO: remove once bootstrap goes GA -->
99
+    <repositories>
100
+        <repository>
101
+            <id>spring-snapshots</id>
102
+            <url>http://repo.springsource.org/snapshot</url>
103
+            <snapshots><enabled>true</enabled></snapshots>
104
+        </repository>
105
+    </repositories>
106
+    <pluginRepositories>
107
+        <pluginRepository>
108
+            <id>spring-snapshots</id>
109
+            <url>http://repo.springsource.org/snapshot</url>
110
+            <snapshots><enabled>true</enabled></snapshots>
111
+        </pluginRepository>
112
+    </pluginRepositories>
113
+</project>
114
+```
115
+
116
+TODO: mention that we're using Spring Bootstrap's [_starter POMs_](../gs-bootstrap-starter) here.
117
+
118
+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.
47 119
 
48 120
 
49 121
 <a name="initial"></a>
@@ -65,7 +137,29 @@ The `id` field is a unique identifier for the greeting, and `content` is the tex
65 137
 
66 138
 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:
67 139
 
68
-    {!include:complete/src/main/java/hello/Greeting.java}
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
+```
69 163
 
70 164
 > **Note:** As you'll see in steps below, Spring will use the _Jackson_ JSON library to automatically marshal instances of type `Greeting` into JSON.
71 165
 
@@ -77,7 +171,30 @@ Create a resource controller
77 171
 
78 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:
79 173
 
80
-    {!include:complete/src/main/java/hello/GreetingController.java}
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
+```
81 198
 
82 199
 This controller is concise and simple, but there's plenty going on under the hood. Let's break it down step by step.
83 200
 
@@ -103,7 +220,23 @@ Although it is possible to package this service as a traditional _web applicatio
103 220
 
104 221
 ### Create a main class
105 222
 
106
-    {!include:complete/src/main/java/hello/Application.java}
223
+`src/main/java/hello/Application.java`
224
+```java
225
+package hello;
226
+
227
+import org.springframework.bootstrap.SpringApplication;
228
+import org.springframework.bootstrap.context.annotation.EnableAutoConfiguration;
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
+```
107 240
 
108 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]_.
109 242
 
@@ -111,7 +244,37 @@ The `@ComponentScan` annotation tells Spring to search recursively through the `
111 244
 
112 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.
113 246
 
114
-### {!include#build-an-executable-jar}
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
+Add the following configuration to your existing Maven POM:
252
+
253
+`pom.xml`
254
+```xml
255
+    <properties>
256
+        <start-class>hello.Application</start-class>
257
+    </properties>
258
+
259
+    <build>
260
+        <plugins>
261
+            <plugin>
262
+                <groupId>org.apache.maven.plugins</groupId>
263
+                <artifactId>maven-shade-plugin</artifactId>
264
+            </plugin>
265
+        </plugins>
266
+    </build>
267
+```
268
+
269
+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`.
270
+
271
+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.
272
+
273
+Now run the following to produce a single executable JAR file containing all necessary dependency classes and resources:
274
+
275
+    mvn package
276
+
277
+[maven-shade-plugin]: https://maven.apache.org/plugins/maven-shade-plugin
115 278
 
116 279
 
117 280
 Run the service

+ 163
- 0
README.src.md Parādīt failu

@@ -0,0 +1,163 @@
1
+# Getting Started: Building a RESTful Web Service
2
+
3
+What you'll build
4
+-----------------
5
+
6
+This guide walks you through creating a "hello world" [RESTful web service][u-rest] with Spring. The service 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
+    {"id":1,"content":"Hello, World!"}
13
+
14
+You can customize the greeting with an optional `name` parameter in the query string:
15
+
16
+    http://localhost:8080/greeting?name=User
17
+
18
+The `name` parameter value overrides the default value of "World" and is reflected in the response:
19
+
20
+    {"id":1,"content":"Hello, User!"}
21
+
22
+
23
+What you'll need
24
+----------------
25
+
26
+ - About 15 minutes
27
+ - {!include#prereq-editor-jdk-buildtools}
28
+
29
+## {!include#how-to-complete-this-guide}
30
+
31
+
32
+<a name="scratch"></a>
33
+Set up the project
34
+------------------
35
+
36
+{!include#build-system-intro}
37
+
38
+{!include#create-directory-structure-hello}
39
+
40
+### Create a Maven POM
41
+
42
+{!include#maven-project-setup-options}
43
+
44
+    {!include:initial/pom.xml}
45
+
46
+{!include#bootstrap-starter-pom-disclaimer}
47
+
48
+
49
+<a name="initial"></a>
50
+Create a resource representation class
51
+--------------------------------------
52
+
53
+Now that you've set up the project and build system, you can create your web service.
54
+
55
+Begin the process by thinking about service interactions.
56
+
57
+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:
58
+
59
+    {
60
+        "id": 1,
61
+        "content": "Hello, World!"
62
+    }
63
+
64
+The `id` field is a unique identifier for the greeting, and `content` is the textual representation of the greeting.
65
+
66
+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:
67
+
68
+    {!include:complete/src/main/java/hello/Greeting.java}
69
+
70
+> **Note:** As you'll see in steps below, Spring will use the _Jackson_ JSON library to automatically marshal instances of type `Greeting` into JSON.
71
+
72
+Next you create the resource controller that will serve these greetings.
73
+
74
+
75
+Create a resource controller
76
+------------------------------
77
+
78
+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:
79
+
80
+    {!include:complete/src/main/java/hello/GreetingController.java}
81
+
82
+This controller is concise and simple, but there's plenty going on under the hood. Let's break it down step by step.
83
+
84
+The `@RequestMapping` annotation ensures that HTTP requests to `/greeting` are mapped to the `greeting()` method.
85
+
86
+> **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.
87
+
88
+`@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.
89
+
90
+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`.
91
+
92
+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.
93
+
94
+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.
95
+
96
+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.
97
+
98
+
99
+Make the application executable
100
+-------------------------------
101
+
102
+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.
103
+
104
+### Create a main class
105
+
106
+    {!include:complete/src/main/java/hello/Application.java}
107
+
108
+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]_.
109
+
110
+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.
111
+
112
+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.
113
+
114
+### {!include#build-an-executable-jar}
115
+
116
+
117
+Run the service
118
+---------------
119
+
120
+Run your service with `java -jar` at the command line:
121
+
122
+    java -jar target/gs-rest-service-0.1.0.jar
123
+
124
+Logging output is displayed. The service should be up and running within a few seconds.
125
+
126
+
127
+Test the service
128
+----------------
129
+
130
+Now that the service is up, visit <http://localhost:8080/greeting>, where you see:
131
+
132
+    {"id":1,"content":"Hello, World!"}
133
+
134
+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!":
135
+
136
+    {"id":2,"content":"Hello, User!"}
137
+
138
+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.
139
+
140
+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.
141
+
142
+
143
+Summary
144
+-------
145
+
146
+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.
147
+
148
+
149
+[zip]: https://github.com/springframework-meta/gs-rest-service/archive/master.zip
150
+[u-rest]: /understanding/rest
151
+[u-json]: /understanding/json
152
+[u-jsp]: /understanding/jsp
153
+[jackson]: http://wiki.fasterxml.com/JacksonHome
154
+[u-war]: /understanding/war
155
+[u-tomcat]: /understanding/tomcat
156
+[u-application-context]: /understanding/application-context
157
+[`@Controller`]: http://static.springsource.org/spring/docs/current/javadoc-api/org/springframework/stereotype/Controller.html
158
+[`SpringApplication`]: http://static.springsource.org/spring-bootstrap/docs/0.5.0.BUILD-SNAPSHOT/javadoc-api/org/springframework/bootstrap/SpringApplication.html
159
+[`@EnableAutoConfiguration`]: http://static.springsource.org/spring-bootstrap/docs/0.5.0.BUILD-SNAPSHOT/javadoc-api/org/springframework/bootstrap/context/annotation/SpringApplication.html
160
+[`@Component`]: http://static.springsource.org/spring/docs/current/javadoc-api/org/springframework/stereotype/Component.html
161
+[`@ResponseBody`]: http://static.springsource.org/spring/docs/current/javadoc-api/org/springframework/web/bind/annotation/ResponseBody.html
162
+[`MappingJackson2HttpMessageConverter`]: http://static.springsource.org/spring/docs/current/javadoc-api/org/springframework/http/converter/json/MappingJackson2HttpMessageConverter.html
163
+[`DispatcherServlet`]: http://static.springsource.org/spring/docs/current/javadoc-api/org/springframework/web/servlet/DispatcherServlet.html