一、REST与RESTful
1、简介
(1)REST(Representational State Transfer):表现层状态转移,一种软件架构风格,不是标准。REST描述的是在网络中client和server的一种交互形式,即资源在网络中以某种表现形式进行状态转移。
(2)基于REST构建的API就是Restful风格。
2、相关概念
(1)资源(Resources):指的是网络上的一个具体的信息(文本、图片等),通过一个URL可以唯一的指向它。
(2)表现层(Representational ):将信息表现出来的形式,比如使用txt表示文本,或者html表示文本。
(3)状态转移(State Transfer):客户端每发送一次请求到服务器,服务器响应会涉及到数据以及状态的切换。而HTTP属于一种无状态的协议,所有状态均保存在服务端,客户端想要去操作服务端,则需要通过某种手段(HTTP协议里的动词)使服务端发生状态转移,且显示在表现层。
3、常见HTTP动词
(1)GET(SELECT): 从服务器获取资源(一项或多项)
(2)POST(CREATE): 在服务器新建一个资源
(3)PUT(UPDATE): 在服务器更新资源(客户端提供改变后的完整资源)
(4)DELETE(DELETE):从服务器删除资源。
4、使用样例
(1)浏览器的 form 表单只支持 GET 与 POST请求,不支持 DELETE、PUT 请求。
(2)Spring 3.0后,添加了一个过滤器(HiddenHttpMethodFilter),可以将POST请求转为DELETE、PUT请求,从而整体支持 DELETE、PUT、GET、POST。
(3)发送 PUT 请求和 DELETE 请求的实现步骤:
step1:需要在web.xml配置 HiddenHttpMethodFilter
step2:需要发送 POST 请求
step3:需要在发送 POST 请求时携带一个 name="_method" 的隐藏域, 值为 DELETE 或 PUT
【主要操作:】 【web.xml中配置 过滤器】 <filter> <filter-name>HiddenHttpMethodFilter</filter-name> <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class> </filter> <filter-mapping> <filter-name>HiddenHttpMethodFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> 【即web.xml】 <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0"> <servlet> <servlet-name>dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:dispatcher-servlet.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcher</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!--配置过滤器,将post请求转为delete,put--> <filter> <filter-name>HiddenHttpMethodFilter</filter-name> <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class> </filter> <filter-mapping> <filter-name>HiddenHttpMethodFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app> 【index.jsp中配置 请求】 <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" isErrorPage="true"%> <html> <head> <title>首页</title> </head> <body> <%--测试get请求--%> <form action="/testRestful/1"> <input type="submit" value="test get"/> </form> <%--测试post请求--%> <form action="/testRe