RESTful学习总结

官方文档1

官方文档2

1 RESTful 是啥

RESTful(Representational State Transfer) 是一种软件架构设计风格。利用URL定位资源,用HTTP方法(GET,POST,DELETE,DETC)描述操作。

1.2 RESTful 特性

(1)资源(Resources):⽹络上的⼀个实体,或者说是⽹络上的⼀个具体信息。它可以是⼀段⽂本、⼀张图⽚、⼀⾸歌曲、⼀种服务,总之就是⼀个具体的存在。可以⽤⼀个 URI(统⼀资源定位符)指向它,每种资源对应⼀个特定的 URI 。要获取这个资源,访问它的 URI 就可以,因此URI 即为每⼀个资源的独⼀⽆⼆的识别符。
(2)表现层(Representation):把资源具体呈现出来的形式,叫做它的表现层 (Representation)。⽐如,⽂本可以⽤ txt 格式表现,也可以⽤ HTML 格式、XML 格式、JSON 格式表现,甚⾄可以采⽤⼆进制格式。
(3)状态转化(State Transfer):每发出⼀个请求,就代表了客户端和服务器的⼀次交互过程。
(4)HTTP 协议:⼀个⽆状态协议,即所有的状态都保存在服务器端。因此,如果客户端想要操作服务器, 必须通过某种⼿段,让服务器端发⽣“状态转化”(State Transfer)。⽽这种转化是建⽴在表现层之上的,所以就是 “ 表现层状态转化” 。具体说, 就是 HTTP 协议⾥⾯,四个表示操作⽅式的动词:GET 、POST 、PUT 、DELETE 。它们分别对应四种基本操作:GET ⽤来获取资源,POST ⽤来新建资源,PUT ⽤来更新资源,DELETE ⽤来删除资源。

总结:看 URL 知道要什么,看 HTTP Method 知道要干什么,看 HTTP Status Code 就知道结果如何

1.3 RESTful 示例

(1)没有 REST 的日子里

原有的url设计:http://localhost:8080/user/queryUserById.action?id=3 ,url中定义了动作(操作),参数具体锁定到操作的是谁

(2)有了REST

有了rest⻛格之后rest中,认为互联⽹中的所有东⻄都是资源,既然是资源就会有⼀个唯⼀的uri标识它,代表它,如

http://localhost:8080/user/3 ,代表的是 id为3 的那个⽤户记录(资源)

锁定资源之后如何操作它呢?

常规操作就是增删改查根据请求⽅式不同,代表要做不同的操作 get 查询,获取资源 post 增加,新建资源 put 更新 delete 删除资源

rest ⻛格带来的直观体现:就是传递参数⽅式的变化,参数可以在 URI 中了

/account/1 HTTP GET :得到 id = 1 的 account

/account/1 HTTP DELETE:删除 id = 1 的 account

/account/1 HTTP PUT:更新 id = 1 的 account

URL:资源定位符,通过 URL 地址去定位互联⽹中的资源(抽象的概念,⽐如图⽚、视频、app服务等)。

1.4 资源的常规操作

(1)GET 获取资源

Retrieve(重新获取) information. Get requests must be safe and idempotent(幂等的), meaning regardless of how many times it repeats with the same parameters, the results are the same. They can have side effects(副作用), but the user doesn't expect them, so they cannot be critical to the operation of the system. Requests can also be partial or conditional.

Retrieve an address with an ID of 1:

GET  /addresses/1

(2)POST 创建或更新资源

Request that the resource at the URI do something with the provided entity. Often POST is used to create a new entity, but it can also be used to update an entity.

Create a new address:

POST  /addresses

(3)PUT 存储或更新实体

Store an entity at a URI. PUT can create a new entity or update an existing one. A PUT request is idempotent. Idempotency is the main difference between the expectations of PUT versus(对比) a POST request.

Modify the address with an ID of 1:

PUT  /addresses/1

(4)PATCH(修补) 更新实体的特定属性

Update only the specified fields of an entity at a URI. A PATCH request is idempotent. Idempotency is the main difference between the expectations of PUT versus(对比) a POST request.

PATCH  /addresses/1

(5)DELETE 移除资源

Request that a resource be removed; however, the resource does not have to be removed immediately. It could be an asynchronous or long-running request.

Delete an address with an ID of 1:

DELETE  /addresses/1

1.5 HTTP status codes

1.1XX-informational

2.2XX-success

3.3XX-redirection

4.4XX-client error

5.5XX-server error

用来传递Server的状态信息。

2 Jersey框架

官网

Jersey是一个基于RESTful请求服务的JAVA框架,与Struts框架类似,它主要用于处理业务逻辑层,同样可以与Hibernate,Spring框架结合。

2.1 入门例子

Jersey project is built using Apache Maven. 在此我以eclipse搭建为例。

step1:File-New-Maven-Maven Project-Next

            

一开始在Filter搜索jersey为空白,这时我们就要手动Add Archetype。点击按钮Add Archetype。然后填入

-Darchetype Artifact Id=jersey-quickstart-grizzly2
-Darchetype Group Id=org.glassfish.jersey.archetypes 
-Darchetype Version=2.26

            

step2:在Filter搜索jersey,选中org.glassfish.jersey.archetypes, 点击Next

step3:按常规的Maven项目填写Group Id..., 点击Finish,项目创建完成。

step4:此时在包路径下有两个类Main.java和MyResource.java,其中Main.java负责启动RESTful服务,而MyResource.java就是我们的RESTful资源。

step5:运行Main.java,在浏览器中输入localhost:8080/myapp/myresource,页面出现"Got it !”,则整个项目搭建完成。

             

3 Spring MVC 支持 RESTful 请求

(1)web.xml

<web-app>
  <!--springmvc提供的针对post请求的编码过滤器,防止乱码-->
  <filter>
    <filter-name>encoding</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>UTF-8</param-value>
    </init-param>
  </filter>

  <!--配置springmvc请求方式转换过滤器,会检查请求参数中是否有_method参数,如果有就按照指定的请求方式进行转换-->
  <filter>
    <filter-name>hiddenHttpMethodFilter</filter-name>
    <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
  </filter>

  <filter-mapping>
    <filter-name>encoding</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

  <filter-mapping>
    <filter-name>hiddenHttpMethodFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

  <servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springmvc.xml</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>

(2)前端 jsp

<div>
        <h2>SpringMVC对Restful风格url的支持</h2>
        <fieldset>
            <p>测试用例:SpringMVC对Restful风格url的支持</p>

            <a href="/demo/handle/15">rest_get测试</a>

            <form method="post" action="/demo/handle">
                <input type="text" name="username"/>
                <input type="submit" value="提交rest_post请求"/>
            </form>

            <form method="post" action="/demo/handle/15/lisi">
                <input type="hidden" name="_method" value="put"/>
                <input type="submit" value="提交rest_put请求"/>
            </form>

            <form method="post" action="/demo/handle/15">
                <input type="hidden" name="_method" value="delete"/>
                <input type="submit" value="提交rest_delete请求"/>
            </form>
        </fieldset>
</div>

(3)后台 Handle 方法

    /*
     * restful  get   /demo/handle/15
     */
    @RequestMapping(value = "/handle/{id}",method = {RequestMethod.GET})
    public ModelAndView handleGet(@PathVariable("id") Integer id) {

        Date date = new Date();
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("date",date);
        modelAndView.setViewName("success");
        return modelAndView;
    }

    /*
     * restful  post  /demo/handle
     */
    @RequestMapping(value = "/handle",method = {RequestMethod.POST})
    public ModelAndView handlePost(String username) {

        Date date = new Date();
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("date",date);
        modelAndView.setViewName("success");
        return modelAndView;
    }

    /*
     * restful  put  /demo/handle/15/lisi
     */
    @RequestMapping(value = "/handle/{id}/{name}",method = {RequestMethod.PUT})
    public ModelAndView handlePut(@PathVariable("id") Integer id,@PathVariable("name") String username) {

        Date date = new Date();
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("date",date);
        modelAndView.setViewName("success");
        return modelAndView;
    }

    /*
     * restful  delete  /demo/handle/15
     */
    @RequestMapping(value = "/handle/{id}",method = {RequestMethod.DELETE})
    public ModelAndView handleDelete(@PathVariable("id") Integer id) {

        Date date = new Date();
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("date",date);
        modelAndView.setViewName("success");
        return modelAndView;
    }

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值