Spring Boot 构建一个 RESTful Web Service

时间:2022-08-25 20:42:51

1  项目目标:

构建一个 web service,接收get 请求

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 目录下 创建的。
Spring Boot 构建一个 RESTful Web Service

3) .2  settings.xml 中 配置本地库 。打开maven 目录下的 conf/settings.xml  文件,修改自己的库目录

Spring Boot 构建一个 RESTful Web Service

3).3 settings.xml 中修改maven镜像下载地址为淘宝,在配置文件中,加入红色代码部分

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

3) .4在idea 中,把maven 改成本地位置。 打开Idea  ,选择File > Settings > 按照如下图配置 本地maven 的三个位置即可。

Spring Boot 构建一个 RESTful Web Service

3  新建项目greeting。 启用spring boot 初始化

Spring Boot 构建一个 RESTful Web Service

输入项目名,我本地取名 quickstart

Spring Boot 构建一个 RESTful Web Service

选择web

Spring Boot 构建一个 RESTful Web Service

创建一个资源 java 类  model

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

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

这个就是返回的结果内: 该类在返回时,会自动被转换成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));
}
}

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

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

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

项目结构:

Spring Boot 构建一个 RESTful Web Service

最后执行:

1   ctrl+F9  编译,确保程序无错误。

2   Shift+F10  启动程序

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

Spring Boot 构建一个 RESTful Web Service

使用 name 参数

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

Spring Boot 构建一个 RESTful Web Service

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

参考spring boot 官方文档资料链接:https://spring.io/guides/gs/rest-service/

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

8080 端口占用解决办法:

打开命令窗口,输入  netstat  –ano

Spring Boot 构建一个 RESTful Web Service

Spring Boot 构建一个 RESTful Web Service

打开任务管理器,找到1572PID 的任务,关掉

Spring Boot 构建一个 RESTful Web Service