This guide is based on a "hello world" RESTful web service with Spring.
You’ll build a service that will accept CRUD (HTTP POST, HTTP GET, HTTP PUT, HTTP DELETE) requests at:
http://localhost:8080/activity
and respond with a JSON representation of an activity (title, text, tags) or a list of activities.
In Spring’s approach to building RESTful web services, HTTP requests are handled by a controller. These components are easily identified by the @RestController
annotation, and the ActivityController
below handles GET
requests for /activity
by returning a new instance of the Activity
class:
src/main/java/hello/ActivityController.java
link:complete/src/main/java/base.activitymeter/ActivityController.java[role=include]
The @RequestMapping
annotation ensures that HTTP requests to /activity
are mapped to the activity()
method.
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 to perform server-side rendering of the activity data to HTML, this RESTful web service controller simply populates and returns an Activity
object. The object data will be written directly to the HTTP response as JSON.
This code uses Spring 4’s new @RestController
annotation, which marks the class as a controller where every method returns a domain object instead of a view. It’s shorthand for @Controller
and @ResponseBody
rolled together.
The Activity
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 is on the classpath, Spring’s MappingJackson2HttpMessageConverter
is automatically chosen to convert the Greeting
instance to JSON.
Although it is possible to package this service as a traditional 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 servlet container as the HTTP runtime, instead of deploying to an external instance.
src/main/java/hello/Application.java
link:complete/src/main/java/base/Application.java[role=include]
Logging output is displayed. The service should be up and running within a few seconds.
The following guides may also be helpful: