Build a restful web Service (Maven version)

Source: Internet
Author: User

[The tutorial is translated from the official spring and is properly truncated.] ]

You will build the

you will build a Web service that can accept HTTP GET requests.   

Http://localhost:8080/greeting
and returns a greeting in the form of a JSON string,

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


Tools

A text editor, JDK1.6 and above, Maven 3.0+ or Gradle 1.11+. (This article will use MAVEN)

The following is a list of the Pom.xml files:

<?xml version= "1.0" encoding= "UTF-8"? ><project xmlns= "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&gt ;spring-boot-starter-parent</artifactid> <version>1.1.5.RELEASE</version> </parent> &            Lt;dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies> < Properties> <start-class>hello. Application</start-class> </properties> <build> <plugins> <plugin> <artif Actid>maven-compiler-plugin</artifactid> <version>2.3.2</version> &LT;/PL Ugin> <plugin> <groupId>org.springframework.boot</groupId> & lt;artifactid>spring-boot-maven-plugin</artifactid> </plugin> </plugins> </bu ild> <repositories> <repository> <id>spring-releases</id> <u rl>http://repo.spring.io/libs-release</url> </repository> </repositories> <pluginrepo sitories> <pluginRepository> <id>spring-releases</id> <url>http:// Repo.spring.io/libs-release</url> </pluginRepository> </pluginRepositories></project>


New Project
First you create a directory structure that conforms to the MAVEN specification, Src/main/java/hello

└──SRC    └──main        └──java            └──hello

Under the Hello directory, create a new greeting class as the JavaBean of the greeting. The code listing is as follows:

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;    }}

In the following steps you will see that spring uses the Jackson JSON to automatically turn the greeting object into a JSON string.


The next step is to create a new class to do the controller.

Building a RESTful Web service in spring requires a controller that handles requests.

Also in the Hello directory, the code listing is as follows:

Package Hello;import Java.util.concurrent.atomic.atomiclong;import Org.springframework.web.bind.annotation.requestmapping;import Org.springframework.web.bind.annotation.requestparam;import Org.springframework.web.bind.annotation.RestController; @RestControllerpublic class Greetingcontroller {    private static final String template = "Hello,%s!";    Private final Atomiclong counter = new Atomiclong ();    @RequestMapping ("/greeting") public    greeting Greeting (@RequestParam (value= "name", Required=false, DefaultValue = "World") String name {        return new greeting (Counter.incrementandget (),                            String.Format (template, name));}    }

Spring MVC has been written about @requestmapping and @requestparam and so on must not be unfamiliar.

The main difference between traditional MVC controllers and RESTful Web service controllers is that they produce HTTP responses in different ways. Unlike dependency view technology, which parses data into HTML, the controller populates and returns an object.

This code uses SPRING4.O new annotations: Restcontroller, which indicates that each method of the class returns an object instead of a view. It is actually a shorthand method for mixed use of @controller and @responsebody.


The greeting object is converted to a JSON string, thanks to spring's HTTP message translation support, which you do not have to handle manually. Since Jackson2 is in Classpath, Spring's mappingjackson2httpmessageconverter will do the job automatically.


Although you can package this service as a traditional war file for deployment to an application server, the following will create a standalone application that uses the main method to package everything into an executable jar file. Also, you will use the support of the sping internal Tomcat servlet container as the HTPP runtime environment and no need to deploy to a Tomcat external instance.

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 uses the Springapplication tool class. This will tell spring to read the meta-information of the application and be managed as a component in the spring application context.

@ComponentScan note tells Spring to traverse the class with @component annotations under the Hello package. This will ensure that spring can find and register greetingcontroller because it is @restcontroller marked, which is also a @component.

@EnableAutoConfiguration annotations Switch to a reasonable default behavior based on the content of your class load path. For example, because the app relies on an inline version of Tomcat (Tomcat-embed-core.jar), all of the Tomcat servers will be booted and configured appropriately instead of you. For example, because the application relies on the Spring MVC Framework (Spring-webmvc.jar), a spring MVC Dispatcherservlet will be configured and registered, and the Web. xml file is no longer required. Automatic configuration is a powerful and flexible mechanism.

This can be done using MAVEN,

MVN Clean Package

Then,

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

The spring boot result will appear without an exception after running:


In the browser test:


Test with parameters:



Build a restful web Service (Maven version)

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.