REST即表述性状态传递(英文:Representational State Transfer,简称REST)是Roy Fielding博士在2000年他的博士论文中提出来的一种软件架构风格。它是一种针对网络应用的设计和开发方式,可以降低开发的复杂性,提高系统的可伸缩性。一种相较与之前URL所产生一种更优雅的URL风格.
查询用户: http://localhost:8080/xxx/user/1 GET —查询
查询多个用户: http://localhost:8080/xxx/users GET
新增用户: http://localhost:8080/xxx/user POST —-新增
修改用户: http://localhost:8080/xxx/user/1 PUT —修改
删除用户:http://localhost:8080/xxx/user/1 DELETE —删除

1.Rest风格

Controller

  1. package com.xixi.controller;
  2. import com.xixi.pojo.User;
  3. import org.springframework.stereotype.Controller;
  4. import org.springframework.web.bind.annotation.*;
  5. /**
  6. * JSPs only permit GET POST or HEAD
  7. * 解决:
  8. * 1.需要添加HiddenHttpMethodFilter过滤器
  9. * 2。在表单中添加隐藏域: <input type="hidden" name="_method" value="put"/> value就是对应的请求方式
  10. * 3。将form表单修改成POST
  11. * 4。过滤器自动将隐藏域修改成value的值。
  12. *
  13. *
  14. *
  15. * Tomcat7以上对request method更为严格,只支持GET/POST
  16. * 1.使用Tomcat7
  17. * 2.不用转发,使用重定向 return "redirect:/index.jsp";
  18. * 3. 将jsp的page指定 isErrorPage属性改成true(不建议)
  19. * 4。自定义一个过滤器,将request.method改回POST
  20. **/
  21. @Controller
  22. @RequestMapping("/rest")
  23. public class RestController {
  24. @GetMapping("/user/{id}")
  25. public String get(@PathVariable("id") Integer id){
  26. System.out.println("查询用户:"+id);
  27. return "/index.jsp";
  28. }
  29. // 新增
  30. @PostMapping("/user")
  31. public String add(User user){
  32. System.out.println("新增用户:"+user);
  33. return "/index.jsp";
  34. }
  35. //修改
  36. @PutMapping("/user/{id}")
  37. public String update(User user){
  38. System.out.println("修改用户:"+user);
  39. return "/index.jsp";
  40. // return "redirect:/index.jsp";
  41. }
  42. //删除
  43. @DeleteMapping("/user/{id}")
  44. public String delete(@PathVariable("id") Integer id){
  45. System.out.println("删除用户:"+id);
  46. return "/index.jsp";
  47. // return "redirect:/index.jsp";
  48. }
  49. }

2.rest.jsp

<%--
  Created by IntelliJ IDEA.
  User: yangkang
  Date: 2021/11/11
  Time: 20:47
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<% request.setAttribute("basepath",request.getContextPath()); %>
<html>
<head>
    <title>Title</title>
</head>
<body>

<form action="${basepath}/rest/user/1" method="get">


    <input type="submit" value="查询"/>

</form>

<form action="${basepath}/rest/user" method="post">
    id:<input type="text" name="id" />
    姓名:<input type="text" name="name" />
    <input type="submit" value="新增"/>
</form>

<!-- html不识别put和delete-->
<%--<form action="${basepath}/rest/user/1" method="put">--%>
<form action="${basepath}/rest/user/1" method="post">
    id:<input type="text" name="id" />
    姓名:<input type="text" name="name" />
    <input type="submit" value="修改"/>
    <input type="hidden" name="_method" value="put"/>
</form>

<%--<form action="${basepath}/rest/user/1" method="delete">--%>
<form action="${basepath}/rest/user/1" method="post">
    <input type="submit" value="删除"/>
    <input type="hidden" name="_method" value="delete"/>
</form>






</body>
</html>

3.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">


    <!--DispatchServlet的配置 分发器 -->
    <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:spring-mvc.xml</param-value>
        </init-param>
        <!-- TOMCAT容器启动的时候下载-->
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>


    <!-- 从上往下加载filter-->
    <filter>
           <filter-name>characterEncodingFilter</filter-name>
           <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
           <!--解决post请求乱码-->
           <init-param>
             <param-name>encoding</param-name>
             <param-value>UTF-8</param-value>
           </init-param>
           <!--解决响应乱码-->
           <init-param>
             <param-name>forceEncoding</param-name>
             <param-value>true</param-value>
           </init-param>
         </filter>
     <filter-mapping>
       <filter-name>characterEncodingFilter</filter-name>
       <url-pattern>/*</url-pattern>
     </filter-mapping>


    <!-- 处理html中不支持rest中put和delete-->
    <filter>
        <filter-name>hiddenHttpMethodFilter</filter-name>
        <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>hiddenHttpMethodFilter</filter-name>
        <servlet-name>springmvc</servlet-name>
    </filter-mapping>


    <!-- 自定义一个过滤器,将request.method改回POST-->
    <filter>
        <filter-name>myFilter</filter-name>
        <filter-class>com.xixi.GetMethodConvertingFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>myFilter</filter-name>
        <url-pattern>/*</url-pattern>
        <dispatcher>FORWARD</dispatcher>
    </filter-mapping>
</web-app>

3.自定义Filter解决PUT/DELETE回显报错

package com.xixi;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.IOException;

/**
 * @author yangkang
 * @version 1.0
 * @description: TODO
 * @date 2021/11/12 00:59
 */
public class GetMethodConvertingFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        filterChain.doFilter(wrapperRequest((HttpServletRequest) servletRequest),servletResponse);

    }

    @Override
    public void destroy() {

    }

    private HttpServletRequestWrapper wrapperRequest(HttpServletRequest request) {
        return new HttpServletRequestWrapper(request){
            @Override
            public String getMethod() {
                return "POST";
            }
        };
    }
}

2.访问静态资源

此时大家发现我们请求的图片根本访问不到,根据查看发现路径是没有问题的,那么为什么会找不到静态资源呢?
image.png大家发现此时是找不到对应的mapping映射的,此时是因为DispatcherServlet会拦截所有的请求,而此时我们没有对应图片的请求处理方法,所以此时报错了,想要解决的话非常简单,只需要添加一个配置即可.

2.1 spring-mvc.xml


    <!--配置访问静态资源 -->
    <mvc:annotation-driven/>

    <!-- 1。将映射的路径指向静态资源文件夹,springmvc将不会将此作为handler处理(推荐)-->
<!--    <mvc:resources mapping="/images/**" location="/images/"></mvc:resources>-->

    <!--2。当springmvc 没有映射到一个请求的时候交给tomcat默认的servlet处理 -->
    <mvc:default-servlet-handler></mvc:default-servlet-handler>