当前位置: 移动技术网 > IT编程>开发语言>Java > 玩转 SpringBoot 2 快速搭建 | RESTful Api 篇

玩转 SpringBoot 2 快速搭建 | RESTful Api 篇

2019年08月31日  | 移动技术网IT编程  | 我要评论

概述

restful 是一种架构风格,任何符合 restful 风格的架构,我们都可以称之为 restful 架构。我们常说的 restful api 是符合 restful 原则和约束的 http 协议的web 接口,需要注意的是它和 http 协议并非绑定关系。我的个人理解就是:通过http协议不同请求方法(get、post、put、patch,delete)来判断如何操作统一命名的资源,并且通过不同的响应码来知道执行的状态。

关于 restful api 具体详细介绍,我推荐阅读下面 3 篇博客:
api设计:https://docs.microsoft.com/en-us/azure/architecture/best-practices/api-design by microsoft azure
restful api设计:让您的用户满意的13个最佳实践:https://blog.florimond.dev/restful-api-design-13-best-practices-to-make-your-users-happy by florimond manca
restful api 最佳实践:http://www.ruanyifeng.com/blog/2018/10/restful-api-best-practices.html by 阮一峰

正如 restful api设计:让您的用户满意的13个最佳实践中所说:i have no authority to say that the following practices comply 100% with the holy rest principles (if there is such a thing!).
我没有权力说下面的做法100%符合神圣的rest原则(如果有这样的话!)。
我也不敢保证我的这篇文章绝对符合 rest ,但是我会尽最大努力向 rest 靠拢。

文中为了快速展示前台 restful 使用操作,所以示例并没有对接数据库,示例代码只是写死的逻辑返回。后期文章会将这个洞补上。

本文代码示例是在 springboot 上进行操作的,如果你不会搭建sprignboot项目可以查看我关于 springboot 2 快速搭建 3 篇总结:
玩转springboot 2 快速搭建 | spring initializr 篇
玩转 springboot 2 快速搭建 | springtoolsuite 篇
玩转 springboot 2 快速搭建 | intellj idea篇

示例程序环境版本:
springboot version:2.1.0.release
springmvc version:5.1.2release
maven version:3.2.5
jdk version:1.8.0_144

实战

用户 model 的代码:

下面是用户的 model 类,用户类里面包含用户名称和用户年龄 2 个成员变量。

package cn.lijunkui.springbootlearn.restful.model;

public class user {
    private string name;
    private integer age;
    //省略get and set 方法
}

用户接口 controller 类:

@restcontroller()
@requestmapping("/user")
public class usercontroller {
    
    logger log = loggerfactory.getlogger(usercontroller.class);
    
    /**
     * 根据用户id 查询用户
     * @return
     */
    @getmapping("/{id}")
    public responseentity<user> get(@pathvariable(name = "id") long id){
        user user = new user("lijunkui",18);
        log.info("查询用户成功:"+"id:{}",id);
        return responseentity.ok(user);
    }
    /**
     * 查询所有的用户
     * @return
     */
    @getmapping("/")
    public responseentity<list<user>> getall(){
        
        list<user> userlist = new arraylist<user>(){{
            add(new user("lijunkui1",18));
            add(new user("lijunkui2",18));
            add(new user("lijunkui3",18));
        }};
        return  responseentity.ok(userlist);
    }
    /**
     * 添加用户
     */
    @postmapping("/")
    public responseentity<user> add(@requestbody user user){
        log.info("添加用户成功:"+"name:{},age:{}",user.getname(),user.getage());
        return  responseentity.status(httpstatus.created).body(user);
    }
    /**
     * 更新用户
     * @param user
     * @return
     */
    @putmapping("/")
    public  responseentity<void> updateput(@requestbody user user){
        log.info("修改用户成功:"+"name:{},age:{}",user.getname(),user.getage());
        return responseentity.ok().build();
    }
    /**
     * 局部更新
     * @return 
     */
    @patchmapping("/{name}")
    public responseentity<void> updatepatch(@pathvariable("name") string name){
        log.info("修改用户成功:"+"name:{}",name);
        return responseentity.ok().build();
    }
    /**
     * 删除用户
     */
    @deletemapping("/{id}")
    public responseentity<void> delete(@pathvariable("id") long id){
        log.info("删除用户成功:"+"id:{}",id);
        return  responseentity.status(httpstatus.no_content).build();
    }
}

@restcontroller():声明在 controller 上,表明该 controller 为 restful 风格的controller。

该注解在 spirng 4.0 中也同样适用,但是在springmvc 3.0 中我们需要通过@controller 和
@responsebody 来达到 @restcontroller()的效果。

@getmapping():声明使用 get 方式访问的接口,该方式主要用于数据查询。

@postmapping():声明使用 post方式访问的接口,该方式主要用于数据新增。

@putmapping():声明使用 put方式访问的接口,该方式主要用于全部更新。

@patchmapping():声明使用 patch方式访问的接口,该方式主要用于局部更新。

@deletemapping():声明使用 delete 方式访问的接口,该方式主要用于数据删除。

对于@getmapping() 和 @postmapping() == @requestmapping(value = "",method
= requestmethod.get) @requestmapping(value = "",method = requestmethod.post) 。

responseentity :用于封装响应回客户端数据和响应状态码的。常用用法如下:

responseentity.ok().build():表示无返回数据,并且响应状态码是 200
responseentity.ok(user):表示有回数据,并且响应状态码是 200
responseentity.status(httpstatus.no_content).build():表示无返回数据,并且响应状态码是 204
responseentity.status(httpstatus.created).body(user):表示有返回数据,并且响应状态码是 201

@putmaping() bug

put 方式接受不到参数问可以通过配置 httpputformcontentfilter 来解决。具体处理代码如下:

/**
 * 解决restful put 参数无法接收的问题
 */
@component
public class putfilter extends httpputformcontentfilter {
}

参考文献:https://www.aliyun.com/jiaocheng/852091.html

测试

restful 接口测试是通过 postman 来进行演示的,你也可以选择你顺手的工具进行测试哈。

根据用户id 查询用户:选择 get 调用方式,然后在地址栏输入: localhost:8080/sbe/user/1 最后点击 send。如下图所示成功返回用户信息和200 响应码。

在这里插入图片描述

查询所有的用户:选择 get 调用方式,地址栏输入 localhost:8080/sbe/user/。
在这里插入图片描述

添加用户:选择 post 调用方式,地址栏输入 localhost:8080/sbe/user/ 。选择body -- json(application/json) 输入要添加用户json 信息。如下图所示:
在这里插入图片描述

修改用户: 选择 put 调用方式,地址栏输入 localhost:8080/sbe/user/ 。选择body -- json(application/json) 输入要修改用户json 信息。如下图所示:
在这里插入图片描述

修改用户:选择 patch 调用方式,地址栏输 localhost:8080/sbe/user/你想要修改的名称。如下图所示:
在这里插入图片描述

删除用户:选择 delete 调用方式,地址栏输入: localhost:8080/sbe/user/1。如下图所示: 在这里插入图片描述

小结

springboot 开发 restful api 还是比较简单的,将 controller 通过 @restcontroller 声明后 在通过具体的动作mapping注解 + responseentity 定义返回数据和响应的状态码 基本就可以搞定。如果你没有操作过,建议跟着博客敲一遍哈。

代码示例

本文具体代码可以查看我的 github 仓库 springbootexamples 中模块名为 spring-boot-2.x-restful-api 的 cn.lijunkui.restful.basic包下进行查看

github:https://github.com/zhuoqianmingyue/springbootexamples 如果您对这些感兴趣,欢迎 点个赞或者关注给予支持!

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网