搭建一个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 启动并把项目部署在里面。

目录
相关文章
|
12天前
|
XML 前端开发 JavaScript
RESTful Web Services
RESTful Web Services
14 2
|
19天前
|
SQL 缓存 测试技术
RESTful API设计的最佳实践:构建高效、可维护的Web服务接口
【6月更文挑战第11天】构建高效、可维护的RESTful API涉及多个最佳实践:遵循客户端-服务器架构、无状态性等REST原则;设计时考虑URL结构(动词+宾语,使用标准HTTP方法)、使用HTTP状态码、统一响应格式及错误处理;确保数据安全(HTTPS、认证授权、输入验证);实施版本控制;并提供详细文档和测试用例。这些实践能提升Web服务接口的性能和质量。
|
23天前
|
JSON 前端开发 API
Apache HttpClient调用Spring3 MVC Restful Web API演示
Apache HttpClient调用Spring3 MVC Restful Web API演示
18 1
|
23天前
|
JavaScript 前端开发 定位技术
Rest风格WEB服务(Rest Style Web Service)的真相
Rest风格WEB服务(Rest Style Web Service)的真相
34 1
|
4天前
|
安全 Java 测试技术
开发Java RESTful Web服务的技巧
开发Java RESTful Web服务的技巧
|
1月前
|
XML API 网络架构
Web Service和Web API理解和使用场景
**Web Service**是一种基于网络、使用SOAP协议和XML的数据封装的重服务,适用于跨平台、跨语言的企业系统集成,尤其在安全性和事务处理严格的场景,如银行系统。而**Web API**是轻量级的HTTP接口,常遵循REST原则,使用JSON格式,适合移动应用、开放平台和微服务间的通信,因其简洁高效。选择哪种取决于项目需求,Web Service适合复杂交互,Web API则流行于现代Web应用。
|
1月前
|
Java API 数据库
利用Java构建高性能的RESTful Web服务
在现代软件开发中,RESTful Web服务已成为一种流行的架构模式,用于构建可扩展、可维护的网络应用。本文将探讨如何使用Java编程语言及其相关框架(如Spring Boot)来构建高性能的RESTful Web服务。我们将不仅仅关注基本的RESTful API设计,还将深入讨论性能优化、安全性、以及服务扩展性等方面的技术细节。通过本文,读者将能够掌握构建高效RESTful Web服务的核心技术和实践。
|
26天前
|
XML JSON API
RESTful API关键部分组成和构建web应用程序步骤
RESTful API关键部分组成和构建web应用程序步骤
17 0
|
1月前
|
应用服务中间件 API nginx
使用Python和Flask构建RESTful Web API
使用Python和Flask构建RESTful Web API
37 0
|
1月前
|
缓存 应用服务中间件 数据库
Python Web Service开发及优化
随着互联网的快速发展,Web服务已成为现代技术的核心。Python作为一种功能强大且易于学习的编程语言,在Web服务开发领域占据着重要地位。Python Web服务开发的重要性在于它能够提供高效、可扩展且易于维护的解决方案。本篇博客将探讨如何使用Python的Flask框架、Gunicorn WSGI服务器和Nginx网页服务器来实现高性能的Web服务。