美文网首页30分钟学会spring
[原创]1.创建一个 RESTful web服务

[原创]1.创建一个 RESTful web服务

作者: 哈士奇18 | 来源:发表于2019-07-23 20:09 被阅读0次

学习 如何用spring创建一个 RESTful web 服务.

开始吧!

创建一个 RESTful web 服务.

本指南将引导您完成使用Spring创建“hello world”RESTful Web服务的过程。

实现的效果:

构建一个接受HTTP GET请求的服务:

http://localhost:8080/greeting

响应为如下JSON字符串:

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

可以使用查询字符串中的可选name参数自定义响应

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

name参数值将覆盖默认值“World”并反映在响应中:

{"id":1,"content":"Hello, User!"}
项目结构
└── src

    └── main

        └── java

            └── hello
pom.xml
<?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 https://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>2.1.6.RELEASE</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.jayway.jsonpath</groupId>
            <artifactId>json-path</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <properties>
        <java.version>1.8</java.version>
    </properties>


    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>



 

1.创建一个实体类

设置好项目结构,开始创建 web 服务.

该服务将处理/ greetingGET请求,(可选)在查询字符串中使用name参数。 GET请求应返回一个“200 OK”响应,其中JSON位于 正文中。 它应该看起来像这样:

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

id字段是 唯一标识符,content是 文本内容。
创建一个名为greeting的类包含idcontent属性,和构造函数 ,包名为hello

src/main/java/hello/Greeting.java

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

Spring使用Jackson JSON库自动把Greeting类封装为JSON实例。

2.创建一个controller类

在Spring构建RESTful Web服务的方法中,HTTP请求由控制器处理。 这些组件可以通过@RestController注释轻松识别,下面的GreetingController通过返回Greeting类的新实例来处理/ greeting的GET请求:
src/main/java/hello/GreetingController.java

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;

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

@RequestMapping注解确保 /greeting的HTTP请求映射到greeting()方法中。

上面 未指定GETPUTPOST等,因为@RequestMapping默认映射所有HTTP操作。 使用@RequestMapping(method = GET)可以缩小映射范围。
@RequestParam将查询字符串参数名称的值绑定到greeting()方法的name参数中。 如果请求中不存在name参数,则使用默认值“World” 。

greeting()方法返回一个新的Greeting对象.id自增加1,nametemplate字符串模板格式化,也就是返回 类似Hello XXX!

传统MVC控制器和上面的RESTful Web服务控制器之间的关键区别在于一个是返回HTML页面,一个返回的是JOSN对象.

此代码使用Spring 4的新@RestController注释,它将类标记为控制器,其中每个方法都返回一个 JOSN对象而不是视图。 这是@Controller和@ResponseBody汇总在一起的简写。

Greeting对象必须转换为JSON。 由于 Jackson 2类库 会自动选择Spring的MappingJackson2HttpMessageConverter将Greeting实例转换为JSON,无需手动转换。

运行程序

创建运行类
src/main/java/hello/Application.java

package hello;

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

@SpringBootApplication
public class Application {

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

@SpringBootApplication是一个方便的 注解,添加了以下所有内容:

  • @Configuation等价于<Beans></Beans>

    @Bean等价于<Bean></Bean>

    @ComponentScan等价于<context:component-scan base-
    package="com.xxx"/>

  • @EnableAutoConfiguration 告诉spring根据 classpath 和 定义的
    bean和各种属性设置来添加bean类.

  • 通常你会为Spring MVC应用程序添加@EnableWebMvc,但
    Spring Boot会在类路径上看到spring-webmvc时自动添加它。 这
    会 将应用程序标记为Web应用程序并激活关键行为,例如设置
    DispatcherServlet。

  • @ComponentScan告诉Spring在hello包中寻找其他组件,配置和
    服务,允许它找到控制器。

main()方法使用Spring Boot的SpringApplication.run()方法来启动应用程序。 注意到没有一行XML? 也没有web.xml文件。 此Web应用程序是100%纯Java,无需处理任何配置 。

建立一个可执行的 JAR

利用maven打包war或者jar运行,这里不做介绍.
java -jar target/gs-rest-service-0.1.0.jar

测试服务

访问 http://localhost:8080/greeting, 将出现下面结果:

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

访问 http://localhost:8080/greeting?name=User. 将出现下面结果:

{"id":2,"content":"Hello, 张三!"}

相关文章

网友评论

    本文标题:[原创]1.创建一个 RESTful web服务

    本文链接:https://www.haomeiwen.com/subject/dvgalctx.html