Spring Boot 構建一個 RESTful Web Service

1  項目目標:css

構建一個 web service,接收get 請求html

http://localhost:8080/greeting
響應一個json 結果:
{"id":1,"content":"Hello, World!"}
能夠在請求中添加自定義參數name
http://localhost:8080/greeting?name=User
響應結果:
{"id":1,"content":"Hello, User!"}
 
2 環境準備:
1) 開發工具 IntelliJ IDEA  (本身下載安裝) cdkey 網上找吧。
2) JAVA JDK1.8+   (http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html)   //  本示例是用的 jdk1.8.0_172   Windows x64
2).1  配置 JDK 環境變量。 http://www.cnblogs.com/iampkm/p/8805493.html
根據JDK 的安裝路徑,在系統環境變量中配置 (JAVA_HOME,PATH,CLASSPATH)
3) 配置Maven 3.2+   下載:https://maven.apache.org/download.cgi  (我用的是3.5)
3).1 新建本地庫目錄repository (位置能夠隨意)。我是在apache-maven-3.5.2 目錄下 建立的。
image

3) .2  settings.xml 中 配置本地庫 。打開maven 目錄下的 conf/settings.xml  文件,修改本身的庫目錄java

image

3).3 settings.xml 中修改maven鏡像下載地址爲淘寶,在配置文件中,加入紅色代碼部分web

  <mirrors>
    <!-- mirror
     | Specifies a repository mirror site to use instead of a given repository. The repository that
     | this mirror serves has an ID that matches the mirrorOf element of this mirror. IDs are used
     | for inheritance and direct lookup purposes, and must be unique across the set of mirrors.
     |
    <mirror>
      <id>mirrorId</id>
      <mirrorOf>repositoryId</mirrorOf>
      <name>Human Readable Name for this Mirror.</name>
      <url>http://my.repository.com/repo/path</url>
    </mirror>
     -->
    <mirror>
    <id>alimaven</id>
    <name>aliyun maven</name>
    <url>
http://maven.aliyun.com/nexus/content/groups/public/</url>
    <mirrorOf>central</mirrorOf>      
    </mirror>

  </mirrors>spring

3) .4在idea 中,把maven 改爲本地位置。 打開Idea  ,選擇File > Settings > 按照以下圖配置 本地maven 的三個位置便可。apache

image

3  新建項目greeting。 啓用spring boot 初始化json

image

輸入項目名,我本地取名 quickstartapi

image

選擇webspringboot

image

建立一個資源 java 類  modelintellij-idea

Create a resource representation class

Now that you’ve set up the project and build system, you can create your web service.

Begin the process by thinking about service interactions.

The service will handle GET requests for /greeting, optionally with a name parameter in the query string. The GET request should return a 200 OK response with JSON in the body that represents a greeting. It should look something like this:

package com.example.qucikstart;

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

這個就是返回的結果內: 該類在返回時,會自動被轉換成json格式

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

建立一個java 控制類  GreetingController

Create a resource controller

In Spring’s approach to building RESTful web services, HTTP requests are handled by a controller. These components are easily identified by the @RestController annotation, and the GreetingController below handles GET requests for /greeting by returning a new instance of the Greeting class:

package com.example.qucikstart;

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;

@RestController
public class GreetingController {
    private static final  String template ="hello,%s!";
    private  final  AtomicLong counter = new AtomicLong();

    @RequestMapping("/Greeting")
    public Greeting greeting(@RequestParam(value="name",defaultValue="world") String name) {
        return new Greeting(counter.incrementAndGet(),
                String.format(template, name));
    }
}

This controller is concise and simple, but there’s plenty going on under the hood. Let’s break it down step by step.

The @RequestMapping annotation ensures that HTTP requests to /greeting are mapped to the greeting() method.

當請求 RequestMapping 註解會把 greeting 的請求,映射到 greeting 方法。

 

確保main 程序用springboot 啓動

Make the application executable

Although it is possible to package this service as a traditional WAR file for deployment to an external application server, the simpler approach demonstrated below creates a standalone application. You package everything in a single, executable JAR file, driven by a good old Java main() method. Along the way, you use Spring’s support for embedding the Tomcat servlet container as the HTTP runtime, instead of deploying to an external instance.

package com.example.qucikstart;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class QucikstartApplication {

    public static void main(String[] args) {
        SpringApplication.run(QucikstartApplication.class, args);
    }
}

項目結構:

image

 

最後執行:

1   ctrl+F9  編譯,確保程序無錯誤。

2   Shift+F10  啓動程序

Now that the service is up, visit http://localhost:8080/greeting, where you see:

image

使用 name 參數

http://localhost:8080/greeting?name=java

image

到此,java spring boot hello 就搞定了。

 

參考spring boot 官方文檔資料連接:https://spring.io/guides/gs/rest-service/

-----------------------------------------------------------------

8080 端口占用解決辦法:

打開命令窗口,輸入  netstat  –ano

image

image

打開任務管理器,找到1572PID 的任務,關掉

image

相關文章
相關標籤/搜索