Build a Spring-based RESTful Web Service

Source: Internet
Author: User
Tags tomcat server git clone

This article details the steps to create a "Hello World" RESTful Web Service project based on spring.

Goal

Build a service that receives the following HTTP GET request:

Http://localhost:8080/greeting

and return the following greeting in JSON format:

{"id": 1, "Content": "Hello, world!"}

You can also customize the greeting by specifying the optional parameter name in the query string:

Http://localhost:8080/greeting?name=User

The value of the parameter name overrides the default value "World" and the resulting response is:

{"id": 1, "Content": "Hello, user!"}
Preparatory work
    • About 15 minutes
    • A text editor or IDE
    • JDK1.6 or higher
    • Gradle 1.8+ or Maven 3.0+
    • You can also import the project directly using the STS (Spring Tool Suite)
How to complete

As with all spring introductory tutorials, you can choose to implement your own step-by-step, or skip the basic setup steps. In the end, you'll get a code that will work.

If you choose to follow the steps, continue to the next section.

If you choose to skip the basic installation section, execute the following command to get the code from GitHub:

git clone https://github.com/spring-guides/gs-rest-service.git

Switch the current directory to gs-rest-service/initial, and skip to the Create a resource representation class step.

When you are done, you can compare it with the code in Gs-rest-service/complete to make sure it is correct.

Establish engineering

Start by building a basic build script. When you build an app based on spring, you can use any build system. Here we take Gradle and Maven as an example. If you are unfamiliar with them, refer to building Java Projects with Gradle or building Java Projects with Maven

Building the directory structure

Under the project directory you selected, create the following subdirectory structure, for example, using the Mkdir-p Src/main/java/hello command in the *nix system:

└──SRC    └──main        └──java            └──hello
Create a Gradle build file

The following is the initial gradle build file. You can also use the Maven,maven configuration file Pom.xml can refer to here. If you use the STS (Spring Tool Suite), you can import the project directly.

Build.gradle

Buildscript {    repositories {        maven {URL "http://repo.spring.io/libs-snapshot"}        mavenlocal ()}    } Apply plugin: ' java ' Apply plugin: ' Eclipse ' Apply plugin: ' idea ' jar {    baseName = ' Gs-rest-service '    version =  ' 0.1.0 '}repositories {    mavencentral ()    maven {URL "http://repo.spring.io/libs-snapshot"}}dependencies {    compile ("Org.springframework.boot:spring-boot-starter-web:1.0.0.rc1")    compile (" Com.fasterxml.jackson.core:jackson-databind ")    testcompile (" junit:junit:4.11 ")}task wrapper (Type:wrapper) {    gradleversion = ' 1.8 '}

Note: This article uses Spring Boot.

Creating Resource Description Classes (Create a resource representation Class)

Now that you have built the engineering and build system, create your Web service below.

First consider the interaction between services (service interactions).

This service handles the GET request for/greeting, whose query string contains an optional name parameter. This get request should be a one-OK response, as well as the content of the description greeting for the JSON structure. The format is as follows:

{    "id": 1,    "content": "Hello, world!"}

The ID field is a unique identifier for the greeting, and the Content field is a textual description of the greeting.

To model the description of a greeting, a resource description class is created. Provides a pojo (pain old Java object) class that contains the domain (ID and content), construction method, and accessor (getter and setter):

Src/main/java/hello/greeting.java

Package Hello;public class Greeting {    private final long id;    Private final String content;    Public greeting (Long ID, String content) {        this.id = ID;        this.content = content;    }    Public long GetId () {        return ID;    }    Public String getcontent () {        return content;    }}

Note: In the following steps, Spring uses the Jackson JSON library to encode an instance of the greeting type into JSON format.

The following is the creation of resource controllers (resource Controller) to send these greetings.

Creating a resource controller (create a resource controller)

When using spring to build restful Web services, the controller handles HTTP requests. The controller component is identified by @controller annotations, and the following Greetingcontroller class handles the/greeting GET request and returns a new instance of the greeting class:

Src/main/java/hello/greetingcontroller.java

Package Hello;import Java.util.concurrent.atomic.atomiclong;import Org.springframework.stereotype.Controller; Import Org.springframework.web.bind.annotation.requestmapping;import Org.springframework.web.bind.annotation.requestparam;import Org.springframework.web.bind.annotation.ResponseBody; @Controllerpublic class Greetingcontroller {    private Static final String template = "Hello,%s!";    Private final Atomiclong counter = new Atomiclong ();    @RequestMapping ("/greeting") public    @ResponseBody Greeting greeting (            @RequestParam (value= "name", required= False, defaultvalue= "World") String name) {        return new greeting (Counter.incrementandget (),                            String.Format ( template, name));}    }

This controller is very simple, but it does a lot of work inside, small, perfectly formed. We explain it step-by-step.

@RequestMapping annotations ensure that HTTP requests to/greeting are mapped to the greeting () method.

Note: The above example does not specify GET, PUT, post, and so on. This is because the @requestmapping annotation maps all HTTP operations by default. Use @requestmapping (method=get) to specify that only GET requests are mapped.

@RequestParam bind the value of the name parameter in the query string to the name parameter of the greeting () method. The query parameter is not required (required=false), and the default value of "World" (defaultvalue) is used if the parameter is not specified when requested.

The implementation of the method body creates and returns a new greeting object with the id attribute of the object each time the self-increment 1,content attribute is combined with the template and name.

A key difference between the traditional MVC controller and the above RESTful Web Service controller is how the HTTP response body is created. The former uses the view-layer technique (technology) to render the server-side data as HTML, while the latter returns a greeting object. The object data will be written directly to the HTTP response in JSON format.

The @responsebody annotation of the greeting () method tells spring MVC not to use the server-side view layer to render the greeting object (the Greeting object), instead, by implementing the above functionality in the following way, Returns the greeting object when a response body, and should be written directly.

The Greeting object must be converted to JSON format. Because spring supports HTTP message conversion, you do not need to convert manually. Because Jackson 2 is in Classpath, Spring's mappingjackson2httpmessageconverter automatically converts greeting instances to JSON format.

Make the application executable

Although this service can be packaged as a traditional war file and deployed to an external application server, we have adopted an easier way: to create a standalone (standalone) application. Package all files into an executable jar file, driven by the old Main () method. Using the embedded Tomcat servlet container provided by spring as the HTTP runtime environment, there is no need to deploy an external runtime environment instance.

Src/main/java/hello/application.java

Package Hello;import Org.springframework.boot.autoconfigure.enableautoconfiguration;import Org.springframework.boot.springapplication;import org.springframework.context.annotation.componentscan;@ Componentscan@enableautoconfigurationpublic class Application {public    static void Main (string[] args) {        Springapplication.run (Application.class, args);}    }

The main () method invokes the Springapplication helper class and passes the Application.class to its run () method as a parameter. Spring then reads the annotations from application and manages them as a component of the spring application context.

@ComponentScan annotations tell spring to recursively search for classes that are directly or indirectly marked as @component in the Hello package and its child packages. This ensures that spring discovers and registers Greetingcontroller, because it is marked as @controller, and @controller is a @component annotation.

@EnableAutoConfiguration annotations Open a reasonable default behavior based on the content of your classpath. For example, because an application relies on an embedded version of Tomcat (Tomcat-embed-core.jar), a Tomcat server automatically establishes and makes a reasonable default configuration. The application also relies on Spring MVC (Spring-webmvc.jar), a spring MVC Dispatcherservlet configures and registers for you – no need for web.xml! Automatic configuration (auto-configuration) is a powerful and flexible mechanism. Please refer to the API documentation for details.

Build executable jar (build an executable jar)

The current position, application class has been written, the following through the building system to package all the files into an executable jar file. This makes it easy to publish, version control, and deploy this service in a variety of different environments.

Here's how to use Gradle, and if you use MAVEN, you can find the Pom.xml file here and execute the MVN clean Package build project.

Update the Buildscript section of the Build.gradle file as follows:

Buildscript {    repositories {        maven {URL "http://repo.spring.io/libs-snapshot"}        mavenlocal ()    }    dependencies {        classpath ("Org.springframework.boot:spring-boot-gradle-plugin:1.0.0.rc1")    }}

Then add the following statement in the Build.gradle:

Apply plugin: ' Spring-boot '

You can see the final version of the Build.gradle file here.

Spring Boot Gradle Plugin collects all the jar packages in the classpath and builds a separate uber-jar, which makes it easier to execute and transfer your service. It also searches public static void for the main () method flag as an executable class.

The following command is executed to generate a separate executable jar file that contains all the required dependent classes and resources:

./gradlew Build

If you use Gradle, you can execute the generated jar file using the following statement:

Java-jar Build/libs/gs-rest-service-0.1.0.jar

If you use MAVEN, use the following statement:

Java-jar Target/gs-rest-service-0.1.0.jar

Note: The above procedure will generate an executable jar. You can also choose to build a war file.

Execute (Run the service)

If you are using Gradle, you can run your service at the command line by executing the following command:

./gradlew Clean Build && Java-jar Build/libs/gs-rest-service-0.1.0.jar

Note: If you use MAVEN, you can execute the following statements MVN Clean package && Java-jar Target/gs-rest-service-0.1.0.jar

Log output. The service will start and run in a few seconds.

Testing (test the service)

Now that the service has started, visit http://localhost:8080/greeting and you will see:

{"id": 1, "Content": "Hello, world!"}

A name parameter, such as Http://localhost:8080/greeting?name=User, is specified in the query string. Content value from "Hello, world!" Change to "Hello, user!" :

{"id": 2, "Content": "Hello, user!"}

This indicates that the @requestparam annotation in the Greetingcontroller class has worked. The default value given by the name parameter is "World", but it can be overridden by setting a value in the query string.

Note The ID property changes from 1 to 2. This indicates that you have accessed the same Greetingcontroller instance in multiple requests, and its counter domain will increment by 1 per visit.

Summary (Summary)

Congratulations! You've developed a spring-based restful Web service.

Build a Spring-based RESTful Web Service

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.