zoukankan      html  css  js  c++  java
  • 实现一个符合 RESTful 架构的程序

    前言:在网上经常看到 RESTful,十分好奇,于是自己来试试。

    代码地址:https://github.com/yuleGH/restdemo

    首先,介绍一下 RESTful 架构:理解 RESTful 架构(转)

    然后,开始尝试

      需求:

      简单实现 CRUD

      设计一下 API:

    • GET  http://localhost:8080/api/users  返回用户列表
    • GET  http://localhost:8080/api/user/1 返回用户 id=1 的数据
    • POST  http://localhost:8080/api/user 创建用户
    • PUT  http://localhost:8080/api/user/1 更新用户 id=1 的数据
    • DELETE  http://localhost:8080/api/user/1 删除用户 id=1 的数据
    • DELETE  http://localhost:8080/api/users 删除所有用户

      使用技术:

      idea + springMVC + maven

      实现:

    1、搭建项目:

    不知道如何搭建这个项目的可以移步 IDEA 搭建 springmvc maven 项目

    2、了解一些注解:

      一般来说你,要实现REST API in Spring 4 需要了解@RestController , @RequestBody, ResponseEntity 和 @PathVariable 这些注解 .另外, spring 也提供了一些支持类帮助你实现一些可定制化的东西。
    • @RestController : 可以移步 @Controller和@RestController的区别(转)
    • @RequestBody : 如果方法参数被 @RequestBody注解,Spring将绑定HTTP请求体到那个参数上。如果那样做,Spring将根据请求中的ACCEPT或者 Content-Type header(私下)使用 HTTP Message converters 来将http请求体转化为domain对象。 
    • @ResponseBody : 如果方法加上了@ResponseBody注解,Spring返回值到响应体。如果这样做的话,Spring将根据请求中的 Content-Type header(私下)使用 HTTP Message converters 来将domain对象转换为响应体。 
    • ResponseEntity 是一个真实数据.它代表了整个 HTTP 响应(response). 它的好处是你可以控制任何对象放到它内部。你可以指定状态码、头信息和响应体。它包含你想要构建HTTP Response 的信息。
    • @PathVariable 此注解意味着一个方法参数应该绑定到一个url模板变量[在'{}'里的一个]中
    • MediaType : 带着 @RequestMapping 注解,通过特殊的控制器方法你可以额外指定,MediaType来生产或者消耗。

    3、给 pom 加一个依赖

        <!--为了返回给前端是 JSON 格式-->
        <dependency>
          <groupId>com.fasterxml.jackson.core</groupId>
          <artifactId>jackson-databind</artifactId>
          <version>2.5.3</version>
        </dependency>

    4、写代码

    5、测试

    根据RestTemplate 写REST Client  

    Spring的 RestTemplate随之出现。RestTemplate 提供了高级方法,来响应者6种主要的HTTP方法。

    HTTP 方法和对应的 RestTemplate方法: 

    • HTTP GET : getForObject, getForEntity
    • HTTP PUT : put(String url, Object request, String…​urlVariables)
    • HTTP DELETE : delete
    • HTTP POST : postForLocation(String url, Object request, String…​ urlVariables), postForObject(String url, Object request, ClassresponseType, String…​ uriVariables)
    • HTTP HEAD : headForHeaders(String url, String…​ urlVariables)
    • HTTP OPTIONS : optionsForAllow(String url, String…​ urlVariables)
    • HTTP PATCH and others : exchange execute

     参考:https://blog.csdn.net/w605283073/article/details/51338765

  • 相关阅读:
    Spring mvc shiro 整合
    Md5
    常用的加密解密算法
    Base64
    java SHA1WithRSA 算法
    jquery使用on绑定change事件,获取input实时输入值
    C#实现将商品金额小写转换成大写
    IIS配置404页面配置,IIS自定义404页面
    HttpWebRequest 基础连接已经关闭: 接收时发生错误
    js css等静态文件版本控制,一处配置多处更新.net版【原创】
  • 原文地址:https://www.cnblogs.com/yuxiaole/p/9537357.html
Copyright © 2011-2022 走看看