This example will review the traditional RESTful service development before jumping deep into Spring Boot.
STS will be used to develop this REST/JSON service.
The following are the steps to develop the first RESTful service:
org.rvslab.chapter2.legacyrest
as the top-level package.legacyrest
.Before proceeding further, pom.xml
needs editing.
4.2.6.RELEASE
, as follows:<org.springframework-version>4.2.6.RELEASE</org.springframework-version>
pom.xml
file for JSON-to-POJO and POJO-to-JSON conversions. Note that the 2.*.*
version is used to ensure compatibility with Spring 4.<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.6.4</version> </dependency>
HomeController.java
to return a JSON value in response to the REST call will do the trick. The resulting HomeController.java
file will look similar to the following:@RestController public class HomeController { @RequestMapping("/") public Greet sayHello(){ return new Greet("Hello World!"); } } class Greet { private String message; public Greet(String message) { this.message = message; } //add getter and setter }
Examining the code, there are now two classes:
Greet
: This is a simple Java class with getters and setters to represent a data object. There is only one attribute in the Greet
class, which is message
.HomeController.java
: This is nothing but a Spring controller REST endpoint to handle HTTP requests.Note that the annotation used in HomeController
is @RestController
, which automatically injects @Controller
and @ResponseBody
and has the same effect as the following code:
@Controller @ResponseBody public class HomeController { }
This should automatically start the server and deploy the web application on the TC server.
If the server started properly, the following message will appear in the console:
INFO : org.springframework.web.servlet.DispatcherServlet - FrameworkServlet 'appServlet': initialization completed in 906 ms May 08, 2016 8:22:48 PM org.apache.catalina.startup.Catalina start INFO: Server startup in 2289 ms
http://localhost:8080/legacyrest/
and display the JSON object as shown in the browser. Right-click on and navigate to legacyrest | Properties | Web Project Settings and review Context Root to identify the context root of the web application:The alternate build option is to use Maven. Right-click on the project and navigate to Run As | Maven install. This will generate chapter2-1.0.0-BUILD-SNAPSHOT.war
under the target folder. This war is deployable in any servlet container such as Tomcat, JBoss, and so on.