Build a restful Web Service with spring

Source: Internet
Author: User

This tutorial will teach you to build a "Hello World" RESTful Web Service with spring.

What will you build

You will build a Web Service to receive HTTP GET requests and request addresses:

http://localhost:8080/greeting
The request response returns a JSON-formatted greeting:
{"id": 1, "Content": "Hello, world!"}

You can add an optional parameter to the request:name, custom greeting:

http://Localhost:8080/greeting?name=user

The value of the name parameter replaces the default "World", and the corresponding response returns to:

{"id": 1, "Content": "Hello, user!"}
What do you need?
    • About 15 minutes
    • Your favorite text editor or IDE
    • JDK1.7 or later
    • Gradle 2.3+ or Maven 3.0+
    • You can also import the code for this tutorial, access the page directly in spring Tool Suite (STS), and then use this as a basis to continue learning.
How to complete this tutorial

Like most spring introductory tutorials, you can complete each step from the beginning, or choose to skip the basic steps that you are already familiar with. In any case, you'll eventually get code that works.

To start from scratch, jump to build with Maven .

To pass the basic step, proceed as follows:

    • Download and unzip the code library for this tutorial, or clone a copy of it with Git:
      git clone https://github.com/spring-guides/gs-rest-service.git
    • Enter the following directory:
      Gs-rest-service/initial
    • Jump to Create resource representation class

When you are done, you can compare your results with the code below to see if they are correct:

Gs-rest-service/complete
Build with Maven

First you have to write a basic build script. You can build a spring application using any of your favorite build systems, but here's the MAVEN code you need. If you are unfamiliar with Maven, refer to building a Java project with Maven .

Create a directory structure

Under the project directory of your choice, create the following subdirectory structure; for example, in the *nix series system, use the following command:

Mkdir-p Src/main/java/hello
└──SRC    └──main        └──java            └──hello

Pom.xml

<?XML version= "1.0" encoding= "UTF-8"?><Projectxmlns= "http://maven.apache.org/POM/4.0.0"Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"xsi:schemalocation= "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">    <modelversion>4.0.0</modelversion>    <groupId>Org.springframework</groupId>    <Artifactid>Gs-rest-service</Artifactid>    <version>0.1.0</version>    <Parent>        <groupId>Org.springframework.boot</groupId>        <Artifactid>Spring-boot-starter-parent</Artifactid>        <version>1.2.3.RELEASE</version>    </Parent>    <Dependencies>        <Dependency>            <groupId>Org.springframework.boot</groupId>            <Artifactid>Spring-boot-starter-web</Artifactid>        </Dependency>    </Dependencies>    <Properties>        <java.version>1.7</java.version>    </Properties>    <Build>        <Plugins>            <plugin>                <groupId>Org.springframework.boot</groupId>                <Artifactid>Spring-boot-maven-plugin</Artifactid>            </plugin>        </Plugins>    </Build>    <repositories>        <Repository>            <ID>Spring-releases</ID>            <URL>Https://repo.spring.io/libs-release</URL>        </Repository>    </repositories>    <pluginrepositories>        <pluginrepository>            <ID>Spring-releases</ID>            <URL>Https://repo.spring.io/libs-release</URL>        </pluginrepository>    </pluginrepositories></Project>

Spring Boot Maven Plugin offers a number of handy features:

    • Collect all the jar packages contained in the classpath and build them into an executable jar package, which makes it easy to run or migrate your Web Serveice.
    • Searches the public static void Main () method and identifies it as an executable class.
    • It provides a built-in dependency resolver that sets the version number to match Spring Boot dependencies. You can override any version of the wish, but it'll default to Boot ' s chosen set of versions. (This paragraph did not understand, dare not to translate)
To create a resource representation class

Now that you've built your project and built your system, you're ready to start creating your Web service.

First think about how Web service interacts.

Your Web service will handle a GET request to the/greeting path, and the request can optionally carry the name parameter. After processing the request, you should return a response with a $ OK, which contains a JSON-formatted greeting statement in the body of the response. Looks like this:

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

The ID field is a unique identifier for a greeting, and the content is the text of the greeting.

To model the concept of greeting, you create a resource representation class, which is a pojo (plain old JAVA object):

Src/main/java/hello/greeting.java
 PackageHello; Public classGreeting {Private Final LongID; Private FinalString content;  PublicGreeting (LongID, String content) {         This. ID =ID;  This. Content =content; }     Public LonggetId () {returnID; }     PublicString getcontent () {returncontent; }}

Note: As you will see, spring will use the Jackson JSON Library to automatically convert the Java object instances of the greeting class into JSON format.

Create a Director (Controller)

The RESTful Web services built by spring uses a controller to process HTTP requests. These components are identified with @restcontroller annotations, and the following Greetingcontroller handles the GET request initiated on the/greeting path, and then returns an instance object of the Greeting class:

Src/main/java/hello/greetingcontroller.java
 PackageHello;ImportJava.util.concurrent.atomic.AtomicLong;Importorg.springframework.web.bind.annotation.RequestMapping;ImportOrg.springframework.web.bind.annotation.RequestParam;ImportOrg.springframework.web.bind.annotation.RestController; @RestController Public classGreetingcontroller {Private Static FinalString template = "Hello,%s!"; Private FinalAtomiclong counter =NewAtomiclong (); @RequestMapping ("/greeting")     PublicGreeting Greeting (@RequestParam (value= "name", defaultvalue= "World") (String name) {return NewGreeting (Counter.incrementandget (), String.Format (template, name)); }}

This controller is simple and concise, but it contains a lot of things. Let's take one by one to parse.

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

Note: The above example does not indicate whether the request type is get or put or post, or any other type, because @requestmapping maps all types of HTTP requests by default. You can use @requestmapping (method=get) to limit the requested type of the mapping.

The @RequestParam assigns the value of the request parameter name to the greeting () method, and the default value for the name parameter is "World" if the name parameter is not carried in the request.

Method creates and returns a newly created greeting object whose id attribute is derived from the next value of counter, and the content property is formatted with the specified name using the format method of the string, with the greeting template.

One of the most critical differences between the traditional MVC controller and the RESTful Web Service controller is the way the HTTP response body is generated. Instead of relying on view technology to turn the greeting object into a html,restful Web service controller on the server side, it simply populates and returns the Greeting object, technology The data in the object is written directly to the HTTP response in JSON format.

This code uses the new annotations in the Sring4 series: @RestController, which identifies a class as a controller, and all of the methods in the controller return a domain object, rather than a view. Previously, @Controller and @resonsebody Two together to achieve this function.

Build a restful Web Service with spring

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.