springMVC如何实现REST风格支持

文章目录

  • 一、REST风格是啥?
  • 二、配置支持REST风格过滤器
  • 三、配置spirngMVC
  • 四、定义控制器
  • 五、前端定义表单

一、REST风格是啥?

REST(Representational State Transfer):表述性状态传递,它是一种针对网络应用的设计和开发方式,可以降低开发的复杂性,提高系统的可伸缩性。

简单来说,HTTP协议本身是无状态的协议,客户端想要操作服务器,可以通过请求资源的方式,将"状态"进行传递。

  • GET请求表示获取资源。
  • POST请求表示新建资源。
  • PUT请求表示更新资源。
  • DELETE请求表示删除资源。

首先我们需要有一个基本的共识就是,浏览器的form表单中,只能有两种请求的方式,GET和POST。那么问题来了,PUT和DELETE如何来表示呢?服务器怎么确认你发的是这俩请求呢?我们需要做些什么呢?

  • 配置支持REST风格的过滤器:HiddenHttpMethodFilter
  • Controller控制器在注解上规定接收方法的方式。
  • 前端通过form表单提交,且提交方式为post,再定义一个名为_method的参数,值为请求方式PUT或DELETE。

原理很简单,我们看看HiddenHttpMethodFilter的源码就知道了:

	//HiddenHttpMethodFilter
	/** Default method parameter: _method */
	public static final String DEFAULT_METHOD_PARAM = "_method";

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {

		HttpServletRequest requestToUse = request;
		//前端必须是post提交的参数
		if ("POST".equals(request.getMethod()) && request.getAttribute(WebUtils.ERROR_EXCEPTION_ATTRIBUTE) == null) {
            //获取名为methodParam的值,其实就是_method的值
			String paramValue = request.getParameter(this.methodParam);
			if (StringUtils.hasLength(paramValue)) {
                //装饰器模式对request进行了增强,重写了getMethod方法:put--> PUT
				requestToUse = new HttpMethodRequestWrapper(request, paramValue);
			}
		}
		//最后放行的是增强后的request
		filterChain.doFilter(requestToUse, response);
	}

二、配置支持REST风格过滤器

<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
                      http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         version="3.0">

    
    <filter>
        <filter-name>characterEncodingFilterfilter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
        <init-param>
            
            <param-name>encodingparam-name>
            <param-value>UTF-8param-value>
        init-param>
        <init-param>
            
            <param-name>forceEncodingparam-name>
            <param-value>trueparam-value>
        init-param>
    filter>
    <filter-mapping>
        <filter-name>characterEncodingFilterfilter-name>
        <url-pattern>/*url-pattern>
    filter-mapping>

    <filter>
        
        <filter-name>hiddenHttpMethodFilterfilter-name>
        <filter-class>org.springframework.web.filter.HiddenHttpMethodFilterfilter-class>
    filter>
    <filter-mapping>
        <filter-name>hiddenHttpMethodFilterfilter-name>
        <url-pattern>/*url-pattern>
    filter-mapping>

    
    <servlet>
        <servlet-name>dispatcherServletservlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
        <init-param>
            <param-name>contextConfigLocationparam-name>
            
            <param-value>classpath:springmvc.xmlparam-value>
        init-param>
        
        <load-on-startup>1load-on-startup>
    servlet>

    <servlet-mapping>
        <servlet-name>dispatcherServletservlet-name>
        
        <url-pattern>/url-pattern>
    servlet-mapping>
web-app>

三、配置spirngMVC


<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

    
    <context:component-scan base-package="com.smday"/>

    
    <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/"/>
        <property name="suffix" value=".jsp"/>
    bean>

    
    <mvc:annotation-driven/>

    
    <mvc:default-servlet-handler/>

beans>

四、定义控制器

@Controller
@RequestMapping("/restful")
public class RestController {

    @RequestMapping(value = "/user/{id}",method = RequestMethod.GET)
    public String getUser(@PathVariable("id") Integer id){
        System.out.printf("==> 查询%d号用户",id);
        return "success";
    }

    @RequestMapping(value = "/user/{id}",method = RequestMethod.DELETE)
    public String deleteUser(@PathVariable("id") Integer id){
        System.out.printf("==> 删除%d号用户",id);
        return "success";
    }

    @RequestMapping(value = "/user/{id}",method = RequestMethod.PUT)
    public String updateUser(@PathVariable("id") Integer id){
        System.out.printf("==> 更新%d号用户",id);
        return "success";
    }

    @RequestMapping(value = "/user",method = RequestMethod.POST)
    public String addUser(){
        System.out.print("==> 添加1号用户");
        return "success";
    }
}

五、前端定义表单

<%--
  Date: 2020/5/2
  Time: 19:50
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
    <head>
        <title>Titletitle>
    head>
    <body>
        <%--增删改查 超链接是get请求 --%>
        <a href="restful/user/1">GET 查询1号用户a><br>

        <form action="restful/user/1" method="post">
            <%--传递一个参数_method ,值为请求类型--%>
            <input name="_method" value="delete">
            <input type="submit" value="DELETE 删除1号用户">
        form>

        <form action="restful/user/1" method="post">
            <input name="_method" value="put">
            <input type="submit" value="PUT 更新1号用户">
        form>

        <form action="restful/user" method="post">
            <input type="submit" value="POST 添加1号用户">
        form>

    body>
html>

你可能感兴趣的:(SpringMVC)