搭建一个RESTful Web Service

简介: 在搭建之前,首先了解一下什么是RESTful,RESTful(Representational state transfer),它并不是一项新技术,而是一种接口规范。

在搭建之前,首先了解一下什么是RESTful,RESTful(Representational state transfer),它并不是一项新技术,而是一种接口规范。

为什么要用RESTful?

因为前后端分离主要是以API为界限进行解耦的,这就会产生大量的API,采用RESTful来统一规范更易于理解且达到解耦目的。
过去客户端向服务器请求资源的url如下:

GET /getStudents
GET /getStudent?id=''
POST /saveStudent
POST /updateStudent
POST /deleteStudent

可以看到,这些请求资源中的动词是没有必要的,如果用RESTful规范的请求,如下:

GET /Students
GET /Students/1 or /Students?id = 1 查找id为1的学生
POST /Student 保存学生
PUT /Student/1 修改学生
DELETE /Student/1 删除学生

RESTful规范规定,所有请求的对象都是资源,都有URI,URI中不能出现动词,只能是名词。


使用Spring来搭建一个简单的RESTful Web Service

我将要实现的效果是通过访问http://localhost:8080/greeting,浏览器返回JSON字符串如下:

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

也可以通过访问http://localhost:8080/greeting?name='zdf',浏览器返回JSON字符串如下:

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

OK, here we go!

step 1 通过maven导入相关包

这里我们使用到了Spring boot,所以需要导入Spring boot的相关jar包,注:Spring boot是简化配置而存在的(个人理解)。

 <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>
<plugin>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
        <artifactId>maven-clean-plugin</artifactId>
        <version>3.0.0</version>
</plugin>
<repositories>
        <repository>
            <id>spring-releases</id>
            <url>https://repo.spring.io/libs-release</url>
        </repository>
    </repositories>
<pluginRepositories>
    <pluginRepository>
        <id>spring-releases</id>
       <url>https://repo.spring.io/libs-release</url>
    </pluginRepository>
</pluginRepositories>

step2 创建一个POJO类

POJO(plain old java object),我觉得它和JavaBean表面上没什么区别,都是Entity Class。

package hello;
/**
 * 描述:
 *
 * @author halo
 * @create 2018-06-30 13:14
 */
public class Greeting {
    private final long id;
    private final String greeting;

    public Greeting(long id, String greeting) {
        this.id = id;
        this.greeting = greeting;
    }

    public long getId() {
        return id;
    }

    public String getGreeting() {
        return greeting;
    }
}

step3 创建一个Controller类

Controller类负责处理客户端的请求,它相当于Struts2的Action,但是它们又有很多不同,如Controller类是基于方法拦截,Struts2的Action是基于类拦截等等。

package hello;
/**
 * 描述:
 *
 * @author halo
 * @create 2018-06-30 13:17
 */
@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));
    }
}

正如上面所看到的,这个Controller类很简洁,但是它的背后做了很多大量的工作,如利用Spring4.x的新特性@RestController来标注这个类是一个Controller,在这个类里面每一个方法所返回的对象将替代以前的视图对象,相当于之前@Controller和@ResponseBody共同使用的功能;那么你可能会问,它是怎么把Greeting转换成JSON对象的呢?这要归功于 Jackson JSON library,因为它被配置在classpath上,Spring会使用自己的MappingJackson2HttpMessageConverter把它会自动转换回JSON对象。

@RequestMapping('/greeting')默认是GET方法请求,当你的请求是/greeting的形式,那么将会被greeting方法拦截;
@RequestParam(value='',defaultValue=''),绑定URI中的参数值到方法参数中,如果请求携带了参数,它会把参数赋值给方法参数name,否则使用默认值;

step4 Done! Make the application executable

创建一个Application类,包含Main方法。

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

当你运行这个程序,你会惊讶的发现,并不需要把此项目打成war包然后再放到Tomcat中,也没有任何.xml文件,包括Web.xml文件,就能把程序运行起来并输入http://localhost:8080/greeting看到我们预期的结果。

why?

这完全要归功于Spring boot,它通过一个注解@SpringBootApplication它完成了SpringMVC中 DispatchServlet的配置,完成了Web.xml的配置,当程序运行时会把内置的Tomcat Servlet 启动并把项目部署在里面。

目录
相关文章
|
1月前
|
JSON API 数据库
解释如何在 Python 中实现 Web 服务(RESTful API)。
解释如何在 Python 中实现 Web 服务(RESTful API)。
26 0
|
2月前
|
IDE Java API
使用Java Web技术构建RESTful API的实践指南
使用Java Web技术构建RESTful API的实践指南
|
1月前
|
前端开发 API 网络架构
Python 如何开发出RESTful Web接口,DRF框架助力灵活实现!
Python 如何开发出RESTful Web接口,DRF框架助力灵活实现!
|
1月前
|
XML JSON API
通过Flask框架创建灵活的、可扩展的Web Restful API服务
通过Flask框架创建灵活的、可扩展的Web Restful API服务
|
1月前
|
JSON API 数据格式
构建高效Python Web应用:Flask框架与RESTful API设计实践
【2月更文挑战第17天】在现代Web开发中,轻量级框架与RESTful API设计成为了提升应用性能和可维护性的关键。本文将深入探讨如何使用Python的Flask框架来构建高效的Web服务,并通过具体实例分析RESTful API的设计原则及其实现过程。我们将从基本的应用架构出发,逐步介绍如何利用Flask的灵活性进行模块化开发,并结合请求处理、数据验证以及安全性考虑,打造出一个既符合标准又易于扩展的Web应用。
653 4
|
1月前
|
存储 缓存 算法
关于 Service Worker 和 Web 应用对应关系的讨论
关于 Service Worker 和 Web 应用对应关系的讨论
13 0
|
2月前
|
API 网络架构
解释 RESTful API,以及如何使用它构建 web 应用程序。
解释 RESTful API,以及如何使用它构建 web 应用程序。
88 0
|
2月前
|
Java API Apache
Apache CXF生成WebService的客户端
Apache CXF生成WebService的客户端
|
2月前
|
缓存 安全 API
深入理解Web开发中的RESTful API设计
在当今快速演进的技术世界中,RESTful API已成为构建现代Web应用不可或缺的一部分。它不仅促进了前后端的分离发展,还为不同平台间的数据交换提供了一种高效、标准化的方式。本文旨在深入探讨RESTful API的设计原则和最佳实践,通过具体示例说明如何设计易于维护、可扩展和安全的API。我们将从REST的基本概念出发,逐步深入到资源命名、HTTP方法的恰当使用、状态码的选择、以及安全性考虑等方面,为读者提供一个全面而深入的视角,帮助大家更好地理解和运用RESTful API。
|
2月前
|
XML 网络架构 数据格式
Ruby 教程 之 Ruby Web Service 应用 - SOAP4R 2
Ruby Web Service 应用 - SOAP4R
24 5