Craig Walls преди 13 години
ревизия
8d5dedeadf
променени са 1 файла, в които са добавени 178 реда и са изтрити 0 реда
  1. 178
    0
      GSRESTService.md

+ 178
- 0
GSRESTService.md Целия файл

@@ -0,0 +1,178 @@
1
+Getting Started: Creating a REST Endpoint
2
+=========================================
3
+
4
+This Getting Started guide will walk you through the process of creating a simple REST endpoint using Spring.
5
+
6
+Setting up Gradle
7
+-----------------
8
+We recommend you use Gradle for your Spring projects. If you’re a big Ant / Ivy, Buildr, Gradle, SBT, Leiningen, or Gant fan, that’s cool, but we use Gradle and we’ll be using Gradle in this guide. If you have any questions about how Gradle works, Building and Testing with Gradle (O'Reilly) should have what you’re looking for. (We’re assuming you know how to create a new Gradle project. If not, you can use this to get started.)
9
+
10
+The following build.gradle file has everything we'll need for our project.
11
+
12
+	apply plugin: 'java'
13
+	apply plugin: 'jetty'
14
+	
15
+	repositories { mavenCentral() }
16
+	
17
+	dependencies {
18
+		compile "org.springframework:spring-webmvc:3.2.2.RELEASE"
19
+		compile "org.codehaus.jackson:jackson-mapper-asl:1.9.9"
20
+	}
21
+
22
+Spring's REST support is based on Spring MVC. Therefore, we must add spring-webmvc as a dependency to our project. Also, so that our endpoints can produce JSON output, we needed to include the Jackson JSON library.
23
+
24
+Each of these dependencies has dependencies of their own that will transitively be resolved.
25
+
26
+We've also included the 'jetty' plugin so that we can easily run and test our code via Gradle.
27
+
28
+
29
+Setting up DispatcherServlet
30
+----------------------------
31
+Spring REST endpoints are built as Spring MVC controllers. Therefore, we'll need to be sure that Spring's DispatcherServlet is configured in our application's /WEB-INF/web.xml:
32
+
33
+	<servlet>
34
+		<servlet-name>appServlet</servlet-name>
35
+		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
36
+		<init-param>
37
+			<param-name>contextClass</param-name>
38
+			<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
39
+		</init-param>
40
+		<init-param>
41
+			<param-name>contextConfigLocation</param-name>
42
+			<param-value>org.springframework.hello.config</param-value>
43
+		</init-param>
44
+		<load-on-startup>1</load-on-startup>
45
+	</servlet>
46
+		
47
+	<servlet-mapping>
48
+		<servlet-name>appServlet</servlet-name>
49
+		<url-pattern>/</url-pattern>
50
+	</servlet-mapping>
51
+
52
+Here we've configured DispatcherServlet to use AnnotationConfigWebApplicationContext as the context class so that our configuration can be expressed in Java, rather than XML. We've also set told DispatcherServlet (via the contextConfigLocation initialization parameter) that it can find our configuration classes in the org.springframework.hello.config package.
53
+
54
+Now let's create the configuration class.
55
+
56
+
57
+Creating a Configuration Class
58
+------------------------------
59
+In our Spring configuration, we'll need to enable annotation-oriented Spring MVC. And we'll also need to tell Spring where it can find our endpoint controller class. The following configuration class takes care of both of those things:
60
+
61
+	package org.springframework.hello.config;
62
+	import org.springframework.context.annotation.ComponentScan;
63
+	import org.springframework.context.annotation.ComponentScan.Filter;
64
+	import org.springframework.context.annotation.Configuration;
65
+	import org.springframework.web.servlet.config.annotation.EnableWebMvc;
66
+	
67
+	@Configuration
68
+	@EnableWebMvc
69
+	@ComponentScan(basePackages="org.springframework.hello", 
70
+	               excludeFilters=@Filter(Configuration.class))
71
+	public class HelloWorldConfiguration {
72
+	}
73
+	
74
+The @EnableWebMvc annotation turns on annotation-oriented Spring MVC. And we've also annotated the configuration class with @ComponentScan to have it look for components (including controllers) in the org.springframework.hello package. As it turns out, classes that are annotated with @Configuration are also discovered by component scanning, so we had to specify an exclude filter to keep it from discovering and using our configuration class a second time.
75
+
76
+With configuration details completed, now it's time to start writing code for our endpoint.
77
+
78
+Creating a Representation Class
79
+-------------------------------
80
+Before we get too carried away with building the endpoint controller, we need to give some thought to what our API will look like. 
81
+
82
+What we want is to handle GET requests for /hello-world, optionally with a name query parameter. In response to such a request, we'd like to send back JSON looking something like this:
83
+
84
+	{
85
+		"id": 1,
86
+		"content": "Hello, stranger!"
87
+	}
88
+	
89
+The id field is a unique identifier for the saying, and content is the textual representation of the saying.
90
+
91
+To model this representation, we’ll create a representation class:
92
+
93
+	package org.springframework.hello;
94
+	
95
+	public class Saying {
96
+	
97
+	  private final long id;
98
+	  private final String content;
99
+	
100
+	  public Saying(long id, String content) {
101
+	    this.id = id;
102
+	    this.content = content;
103
+	  }
104
+	
105
+	  public long getId() {
106
+	    return id;
107
+	  }
108
+	
109
+	  public String getContent() {
110
+	    return content;
111
+	  }
112
+	
113
+	}
114
+
115
+Now that we've got our representation class, let's create the endpoint controller that will serve it.
116
+
117
+Creating a Resource Controller
118
+------------------------------
119
+In Spring, REST endpoints are just Spring MVC controllers. The following Spring MVC controller handles a GET request for /hello-world and returns our Saying resource:
120
+
121
+	package org.springframework.hello;
122
+	import java.util.concurrent.atomic.AtomicLong;
123
+	import org.springframework.stereotype.Controller;
124
+	import org.springframework.web.bind.annotation.RequestMapping;
125
+	import org.springframework.web.bind.annotation.RequestMethod;
126
+	import org.springframework.web.bind.annotation.RequestParam;
127
+	import org.springframework.web.bind.annotation.ResponseBody;
128
+
129
+	@Controller
130
+	@RequestMapping("/hello-world")
131
+	public class HelloWorldResource {
132
+	  
133
+	  private static final String template = "Hello, %s!";
134
+	  private final AtomicLong counter = new AtomicLong();
135
+	
136
+		@RequestMapping(method=RequestMethod.GET)
137
+		public @ResponseBody Saying sayHello(@RequestParam(value="name", required=false, defaultValue="Stranger") String name) {
138
+			return new Saying(counter.incrementAndGet(), String.format(template, name));
139
+		}
140
+		
141
+	}
142
+
143
+The key difference between a human-facing controller and a REST endpoint controller is in how the response is created. Rather than rely on a view (such as JSP) to render model data in HTML, an endpoint controller simply returns the data to be written directly to the body of the response. 
144
+
145
+The magic is in the @ResponseBody annotation. @ResponseBody tells Spring MVC to not render a model into a view, but rather to write the returned object into the response body. It does this by using one of Spring's message converters.
146
+
147
+{TODO: briefly talk about what message converters do and list the ones that come out of the box with Spring}
148
+
149
+
150
+Building and Running the REST Endpoint
151
+--------------------------------------
152
+All of the pieces of our REST endpoint are in place. All that's left to do is to build it and run it.
153
+
154
+To run the sample, issue the following Gradle command:
155
+
156
+	$ gradle jettyRun
157
+	
158
+This will cause the application to be compiled and for a Jetty server to start on port 8080. You can then point your browser or other REST client (such as Spring's RestTemplate or the Spring REST Shell) at http://localhost:8080/HelloWorldRest/hello-world to see the result. Or you can try specifying a name parameter as in http://localhost:8080/HelloWorldRest/hello-world?name=Craig.
159
+
160
+If you simply want to build the code into a WAR file that you can deploy in your own server, issue the following Gradle command:
161
+
162
+	$ gradle build
163
+
164
+
165
+Next Steps
166
+----------
167
+Congratulations! You have just developed a simple REST endpoint using Spring. This is a basic foundation for building a complete REST API in Spring. 
168
+
169
+There's more to building REST APIs than is covered here. You may want to continue your exploration of Spring and REST with the following Getting Started guides:
170
+
171
+* Handling POST, PUT, and GET requests in REST endpoints
172
+* Creating self-describing APIs with HATEOAS
173
+* Securing a REST endpoint with HTTP Basic
174
+* Securing a REST endpoint with OAuth
175
+* Consuming REST APIs
176
+* Testing REST APIs
177
+
178
+