2.Spring Building a rest Web Service

Source: Internet
Author: User
Tags using git

We have already had a preliminary understanding of spring in the previous article, and next we will continue to learn new technologies on our website. Original address: https://spring.io/guides/gs/rest-service/

This guide guides you through the process of creating a "Hello World" REST Web service using spring.

1. What are you going to build?

Tips: As mentioned above, we're going to use spring to create a "Hello World" REST Web service, but what's the end result?

We will build a service that accepts HTTP GET requests:

http://localhost:8080/greeting

When we make the above HTTP Get request, we respond to the JSON content that is returned below.

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

We can also take a parameter to request

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

The Name parameter value overrides the default value of "Word" and is reflected in the response:

{"id": 1, "Content": "Hello, user!"}
2. What will you need to prepare?
    • About 15 minutes

    • A favorite text editor or IDE

    • JDK 1.8 or later

    • Gradle 4+ or Maven 3.2+

    • You can also import the code straight to your IDE:

      • Spring Tool Suite (STS)

      • IntelliJ idea

3. How do I complete this guide?

Like most spriing Getting Started guides, you can start from scratch, complete each step, or you can bypass the basic setup steps you're already familiar with. Anyway, you'll eventually get a work code.

3.1 Getting work Codes

A. Building with Maven

B. Building with Gradle

c. Building with the IDE

    • Read how to use Spring Tool Suite. Building

    • Read how to build with IntelliJ idea

d. Click to download and unzip the warehouse source code

E. Using Git cloning

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

There are five ways to do this, but since we will often use the IDE to do so, here we use the IDE to build the starter Guide project

3.1.1 Getting Started Guide with STS

This guide walks you through using the Spring Tools Suite (STS) to build a getting Started guide.

3.1.1.1 What are you going to build?

You will select the Spring Guide and import it into Spring Tool Suite. Then you can read the guide, process the code, and run the project.

3.1.1.2, what do you need?
    • About 15 minutes

    • Spring Tool Suite (STS)

    • JDK 8 or higher

3.1.1.3 Installing STS

If you have not yet installed the STS, please visit the link above. From there, you can download a copy for your platform. To install it, simply unzip the downloaded archive file.

When you're done, go ahead and log in to STS.

3.1.1.4 Import Getting Started Guide

Start and run with STS and open the import Spring Getting Started Content Wizard from the File menu.

Click file--> New ———— > Import Spring geting Started Content

A window wizard will then pop up to give you the opportunity to search and pick any published guide from the spring website.

You can either browse the list or enter a search term to filter the options immediately.

When providing Instant Search results, the standard applies to headings and descriptions. Wildcard characters are supported.

Enter rest, select Rest Service, click Finish

You can choose Maven or Gradle as the build system to use.

You can also decide whether to crawl the initial code set, complete the code set, or both.

For most projects,

    • (initial) The initial code set is an empty project that allows you to copy and paste your way through the guide
    • The complete code set is all the code from the guide that has been entered. If you catch these two, you can compare your work with the guide's differences.

Finally, you can have the STS open the Browser tab to the guide on the site. This will allow you to work through the wizard without leaving the Sts.

The STS will create two new projects in your workspace, import the consumed Rest code library (initial and complete), and open the Browser tab in the STS as follows:

Tips:

Gs-rest-service-complete is the completed project

Gs-rest-service-initial is to initialize an empty project

3.1.2 Using IntelliJ idea to get started Guide

This guide guides you through using IntelliJ idea to build a getting Started guide.

3.1.2.1 What are you going to build?

You will choose a spring guide and import it into the Itelij idea. Then you can read the guide, process the code, and run the project.

3.1.2.2 What do you need to prepare?
    • 15 minutes

    • IntelliJ idea

    • JDK 6 or higher

3.1.2.3 Installation IntelliJ Idea

If you have not installed IntelliJ idea (Ultimate Edition), please visit the link above. From there, you can download a copy for your platform. To install it, simply unzip the downloaded archive file.

When you're done, continue to start IntelliJ idea

3.1.2.4 Import Getting Started Guide

To import an existing project, you need some code,

Click to download

Or use Git to clone or copy one of the Getting started guides, such as the Rest service guide:

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

Download after decompression

Use IntelliJ idea to start and run, click on the import item on the Welcome screen, or open the file on the main menu:

In the pop-up dialog box, make sure to select Maven's pom.xml or gradle build.gradle file under the full folder:

Here we choose Build.gradle

Intellij idea will create a project with all the code ready to run from the guide.

Keep the default, click OK

After the build is complete

3.2 Creating a resource representation class

Now that you have established the project and established the system, you can create a Web service.

Start the process by considering service interactions.

The service will process the query t/greeting GET request and optionally use the name parameter in the query string. The GET request should return a $ OK response, where JSON is in the body that represents Greetin. It should look like this:

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

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

In order to model the greeting expression, you create a resource representation class. Provides a field, constructor, generic Java object, and access for ID and content data:

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

As you can see in the steps below, Spring uses the Jackson JSON library to automatically marshal instances of the greeting type into JSON.

Next, create a resource controller that will serve these greetings.

3.3 Creating a resource controller

In spring's method of building the rest Web Service, the HTTP request is handled by the controller. These components are easily identified by the @ Restcontroller annotation, and the following Greetingcontroller processes the GET request/greeting by returning a new instance 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)); }}

The controller is simple and straightforward, but there's a lot more to do under the hood. Let's break it step-by-step.

@RequestMapping annotations Ensure that the HTTP request/greeting is mapped to the greeting () method.

The above example does not specify GET, PUT, post, and so on, because @requestmapping maps all HTTP operations by default. Use @requestmapping (method= GET) to narrow this mapping.

@RequestParam bind the value of the query string parameter name to the name parameter of the greeting () method. If the name parameter is missing from the request, the default value of "World" is used.

The implementation of the method body creates and returns a new greeting object with an ID and a content property based on the next value of the counter and formats the given name with the greeting template.

One of the main differences between the traditional MVC controller and the above RESTful Web services controller is how the HTTP response body is created.

Instead of relying on view technology to render the server-side rendering of the greeting data to HTML, this RESTful Web service controller simply populates and returns a greeting object.

The object data is written directly to the HTTP response as JSON.

This code uses the new @restcontroller comment for Spring 4, which marks the class as a controller, where each method returns a domain object instead of a view. It is the abbreviation of @controller and @responsebody.

@RestController = = @Controller + @ResponseBody

The Greeting object must be converted to JSON. Because of the support of the spring HTTP message converter, you do not need to perform this conversion manually.

Because Jackson 2 is in Classpath, Spring's mappingjackson2httpmessageconverter is automatically selected to convert the greeting instance to JSON.

3.4 Making the application executable

Although this service can be packaged as a traditional war file for deployment to an external application server, the simpler approach shown below creates a standalone application.

You package everything into a separate, executable jar file, driven by a good old Java main () method.

Along the journey, you use spring's support to embed the Tomcat servlet container as an HTTP runtime instead of deploying to an external instance.

src/main/java/hello/Application.java

 Package Hello; Import org.springframework.boot.SpringApplication; Import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication  Public class Application {    publicstaticvoid  main (string[] args) {        Springapplication.run (Application. class , args);}    } 

Springbootapplication is a handy note that adds all of the following:

  • @Configuration to mark the class as the source of the bean definition for the application context.
  • @EnableAutoConfiguration notifies spring boot to start adding beans based on the classpath setting, and other beans and various property settings.
  • Typically you will add @enablewebmvc to the Spring MVC application, but spring boot will be added automatically when you see Spring-webmvc in the classpath. This marks the application as a Web application and activates key behaviors, such as setting Dispatcherservlet.
  • @ComponentScan tell spring to look for additional components, configurations, and services in the Hello package to locate the controller.

The main () method launches the application using the Spring Boot Springapplication.run () method. Have you noticed that there is not a single line of XML? No web. xml file. This Web application is 100% pure Java, and you do not have to deal with configuring any pipelines or infrastructure.

3.5 Building an executable jar

You can use Gradle or maven to run the application from the command line. Or you can build an executable jar file that contains all of the required dependencies, classes, and resources, and run the file. This makes it easy to publish, release, and deploy services as applications across different environments throughout the development lifecycle.

If you are using Gradle, you can use the./gradlew Bootrun to run the application. Or you can build a build jar file using./gradlew. Then you can run the jar file:

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

If you are using MAVEN, you can use the./MVNW Spring-boot:run to run the application. Alternatively, you can build the jar file using the./MVNW Clean package. Then you can run the jar file:

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

The above procedure creates a runnable jar. You can also choose to build a classic war file.

Record output display. The service should be up and running within seconds.

3.6 Test Service

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

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

Provide a name parameter to query, Access Http://localhost:8080/greeting?name=User

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

Note that content text has been changed from "Hello, world!" to "Hello, user!"

This change demonstrates that the @requestparam arrangement in Greetingcontroller works as expected. The name parameter has been given the default value of "World", but can always be explicitly overridden by a query string.

Also note how the id attribute is changed from 1 to 2. This proves that you are working on the same Greetingcontroller instance in multiple requests, and that its counter fields increment as expected on each invocation.

Congratulations! You have just developed a restful Web Service with spring.

SOURCE Download: Https://github.com/geekxingyun/JavaEE-Framework-Sample/tree/master/Spring-RESTful-Web-Service-Sample

2.Spring Building a rest 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.