SpringMVC之REST

一、REST概述

REST:Representational State Transfer,也就是(资源)表现层状态转化.

  REST是目前最流行的一种互联网软件架构,它结构清晰、符合标准、易于理解、扩展方便,所以正得到越来越多网站的采用REST.

  1、资源(Resources):网络上的一个实体,或者说是网络上的一个具体信息。它可以是一段文本、一张图片、一首歌曲、一种服务,总之就是一个具体的存在.可以用一个URI(统一资源定位符)指向它,每种资源对应一个特定的URI,获取这个资源,访问它的URI就可以,因此URI即为每一个资源独一无二的识别符.

  2、表现层()Representation):把资源具体呈现出来的形式,叫做它的表现层(Representation).比如,文本可以用 txt 格式表现,也可以用 HTML 格式、XML 格式、JSON 格式表现,甚至可以采用二进制格式.

  3、状态转化(State Transfer):每发出一个请求,就代表了客户端和服务器的一次交互过程.而HTTP协议是一个无状态协议,即所有的状态都保存在服务器端.因此,如果客户端想要操作服务器必须通过某种手段让服务器端发生状态转化(State Transfer).而这种转化是建立在表现层之上的,所以就是所谓的表现层状态转化.

  具体的说就是HTTP协议里面,四个表示操作方式的动词:POST、DELETE、PUT、GET.它分别对应的是添加资源、删除资源、修改资源、查询资源.

二、REST URL风格

  从下面的URL风格可以看出,我们针对用户的操作,URL都是相同的,我们只是通过HTTP的请求方式来确定是对user进行增、删、改、查.

URL HTTP请求方式 具体内容
/user/1 POST 添加id为1的用户信息
/user/1 DELETE 删除id为1的用户信息
/user/1 PUT 修改id为1的用户信息
/user/1 GET 查询id为1的用户信息

  我们都知道,<form>表单只能有POST、GET两种请求方式,我们如何来设置HTTP DELETE 和 HTTP PUT这两种请求方式呢,要设置这两种请求方式就必须借助于HiddenMethodFilter这个过滤器.下面我们看看HiddenHttpMethodFilter这个过滤器的源码

public class HiddenHttpMethodFilter extends OncePerRequestFilter {
    private static final List<String> ALLOWED_METHODS;
    public static final String DEFAULT_METHOD_PARAM = "_method";
    private String methodParam = "_method";

    public HiddenHttpMethodFilter() {
    }

    public void setMethodParam(String methodParam) {
        Assert.hasText(methodParam, "'methodParam' must not be empty");
        this.methodParam = methodParam;
    }

    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws
ServletException, IOException {
        HttpServletRequest requestToUse = request;
        // 请求方式要设置为POST
        if ("POST".equals(request.getMethod()) && request.getAttribute("javax.servlet.error.exception") == null) {
            // this.methodParam的值为"_method",所以form表单中一定要有_method参数,并且获取参数名为_method所对应的值
            String paramValue = request.getParameter(this.methodParam);
            // 如果_method的属性值不为空则进行下一步判断
            if (StringUtils.hasLength(paramValue)) {
                // 将_method参数对应的值进行大小写转换,所以表单中忽略大小写
                String method = paramValue.toUpperCase(Locale.ENGLISH);
                // ALLOWED_METHODS初始化的时候有三个值 PUT DELETE PATCH
                if (ALLOWED_METHODS.contains(method)) {
                    requestToUse = new HiddenHttpMethodFilter.HttpMethodRequestWrapper(request, method);
                }
            }
        }
        // 过滤器放行
        filterChain.doFilter((ServletRequest)requestToUse, response);
    }

    static {
        ALLOWED_METHODS = Collections.unmodifiableList(Arrays.asList(HttpMethod.PUT.name(), HttpMethod.DELETE.name(), HttpMethod.PATCH.name()));
    }

    private static class HttpMethodRequestWrapper extends HttpServletRequestWrapper {
        private final String method;

        public HttpMethodRequestWrapper(HttpServletRequest request, String method) {
            super(request);
            this.method = method;
        }

        public String getMethod() {
            return this.method;
        }
    }
} 

  通过上面我们可以总结出要实现form表单发送DELETE、PUT请求的步骤:

  1、web.xml中配置HiddenHttpMethodFilter

<!--配置过滤器,配置了HiddenHttpMethodFilter这个过滤器之后可以实现让form表单提交HTTP DELETE和HTTP 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>

  2、配置form表单

<%@ page contentType="text/html;charset=UTF-8" language="java" isErrorPage="true" %>
<html>
<head>
    <title>测试@PathVariable注解的method的取值!!!</title>
</head>
<body>
    <form action="${pageContext.request.contextPath}/testHttpMethod/1001" method="POST">
        <input type="submit" value="测试POST提交">
    </form>
    // 要实现发送Delete请求,请求方式必须为POST,请求的参数name必须为"_method",value值为DELETE(也可以delete)
    <form action="${pageContext.request.contextPath}/testHttpMethod/1002" method="POST">
        <input type="hidden" name="_method" value="DELETE">
        <input type="submit" value="测试DELETE提交">
    </form>
    <form action="${pageContext.request.contextPath}/testHttpMethod/1003" method="POST">
        // // 要实现发送Delete请求,请求方式必须为POST,请求的参数name必须为"_method",value值为PUT(也可以put)
        <input type="hidden" name="_method" value="PUT">
        <input type="submit" value="测试PUT提交">
    </form>
    <form action="${pageContext.request.contextPath}/testHttpMethod/1004" method="GET">
        <input type="submit" value="测试GET提交">
    </form>
</body>
</html>

 

  3、控制器

// SpringMVC控制器,此注解必须以@Controller加入到Spring容器中才能被识别为控制器
@Controller
public class SpringmvcDemo {
    
    @RequestMapping(value = "/testHttpMethod/{id}", method = RequestMethod.DELETE)
    // 将请求路径上的可变参数赋值给形参(Integer id)
    public String testSpringMVC01(@PathVariable("id") Integer id) {
        System.out.println("处理DELETE请求");
        System.out.println("请求路径上的参数id为:" + id);
        return "test";
    }
}

  4、测试结果

处理DELETE请求
请求路径上的参数id为:1002

 

原文地址:https://www.cnblogs.com/xiaomaomao/p/13593804.html