springMVC笔记系列(7)——HiddenHttpMethodFilter过滤器

Easter79
• 阅读 356

什么是REST?首先来段介绍吧。

REST: 即 Representational State Transfer。 (资源)表现层状态转化。 是目前最流行的一种互联网软件架构。它结构清晰、符合标准、易于理解、 扩展方便,所以正得到越来越多网站的采用。

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

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

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

状态转化”(State Transfer)。而这种转化是建立在表现层之上的,所以就是 “表现层状态转化”。 具体说, 就是 HTTP 协议里面,四个表示操作方式的动词: GET、 POST、 PUT、 DELETE。它们分别对应四种基本操作: GET 用来获取资源, POST 用来新建资源, PUT 用来更新资源, DELETE 用来删除资源。(本文出自:http://my.oschina.net/happyBKs/blog/416994)

示例:

– /order/1    HTTP  GET : 得到 id =  1 的 order   

– /order/1    HTTP  DELETE: 删除 id = 1 的 order   

– /order/1    HTTP  PUT:更新id = 1 的 order   

– /order      HTTP  POST:新增 order

但是要用spring实现四个方法需要一个过滤器:

HiddenHttpMethodFilter: 浏览器 form 表单只支持 GET与 POST 请求,而DELETE、 PUT 等 method 并不支持, Spring3.0 添加了一个过滤器,可以将这些请求转换为标准的 http 方法,使得支持 GET、 POST、 PUT 与DELETE 请求。

带占位符的 URL 是 Spring3.0 新增的功能, 该功能在SpringMVC 向 REST 目 标挺进发展过程中具有里程碑的意义。

通过 @PathVariable 可以将 URL 中占位符参数绑定到控制器处理方法的入参中: URL 中的 {xxx} 占位符可以通过@PathVariable("xxx") 绑定到操作方法的入参中。

好吧,话不多说,我们实际操练一下,在webapp目录下的原web.xml中添加HiddenHttpMethodFilter过滤器

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>
  
  
  <!-- 配置 org.springframework.web.filter.HiddenHttpMethodFilter,可以吧POST请求转换为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>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
  
  
  
  
  <!--  配置DispatcherServlet -->
  <!-- 下面的代码为STS自动生成,如果是一般的eclipse需要安装springIDE插件 -->
  <!-- The front controller of this Spring Web application, responsible for handling all application requests -->
    <servlet>
        <servlet-name>springDispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!-- 配置DispatcherServlet的一个初始化参数:配置springmvc 配置位置和名称 -->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc.xml</param-value><!-- classpath下的springmvc.xml -->
        </init-param>
        <!-- load-on-startup是指这个servlet是在当前web应用被加载的时候就被创建,而不是第一次被请求的时候被创建 -->
        <load-on-startup>1</load-on-startup>
    </servlet>

<!--     Map all requests to the DispatcherServlet for handling
    /代表可以应答所有请求,由springDispatcherServlet处理 -->
    <servlet-mapping>
        <servlet-name>springDispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

springMVC.xml与之前的文章中的例子相比,没有变化,这里为了读者方便也一起给出,关于springMVC的项目结构和配置请参照我之前的文章。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">

<!-- 配置自动扫描的包 -->
<context:component-scan base-package="com.happyBKs.springmvc.handlers"></context:component-scan>

<!-- 配置视图解析器:如何把handler方法 的返回值 解析为 实际的物理视图-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/views/"></property>
<property name="suffix" value=".jsp"></property>
</bean>


</beans>

接下来写控制器类及其方法,来负责接收和处理请求:RestTestHandler类

package com.happyBKs.springmvc.handlers;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@RequestMapping("/rest")
@Controller
public class RestTestHandler {
    
    /*
     * Rest 风格的Url        原先利用请求参数的风格
     * 以CRUD为例
     * 新增: /order POST        
     * 修改:/order/1 Put         update?id=1
     * 获取:/order/1 GET         get?id=1
     * 删除:/order/1 DELETE        delete?id=1
     * 
     * 如何发送PUT请求和DELETE请求?
     * 1.需要配置HiddenHttpMethodFilter
     * 2.需要发送POST请求
     * 3.需要在发送POST请求时携带一个name=”_method“的隐藏域,值为DELETE或PUT
     *    
     * 在SpringMVC的目标方法中如何得到id呢?
     * 使用@PathVariable注解
     */
    
    
    @RequestMapping(value="/methodstest/{id}",method=RequestMethod.GET)
    public String restGet(@PathVariable int id)//当@PathVariable没有标明{id},
    {
        System.out.println("get "+id);
        System.out.println("querry operations...");
        return "querry";
    }
    
    @RequestMapping(value="/methodstest",method=RequestMethod.POST)
    public String restPost()
    {
        System.out.println("post ");
        System.out.println("post operations...");
        return "post";
    }
    
    @RequestMapping(value="/methodstest/{id}",method=RequestMethod.PUT)
    public String restPut(@PathVariable int id)
    {
        System.out.println("put "+id);
        System.out.println("put operations...");
        return "put";
    }
    
    @RequestMapping(value="/methodstest/{id}",method=RequestMethod.DELETE)
    public String restDelete(@PathVariable int id)
    {
        System.out.println("delete "+id);
        System.out.println("delete operations...");
        return "delete";
    }
}

请求页面编写如下:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
    <a href="rest/methodstest/1">GET Request</a>

    <form action="rest/methodstest" method="post">
        <input type="submit" value="POST Request" />
    </form>

    <form action="rest/methodstest/1" method="post">
        <input type="hidden" name="_method" value="PUT">
        <input type="submit" value="PUT Request" />
    </form>

    <form action="rest/methodstest/1" method="post">
        <input type="hidden" name="_method" value="DELETE">
        <input type="submit" value="DELETE Request" />
    </form>
</body>
</html>

注意到了吗?HiddenHttpMethodFilter帮助我们实现对put请求和delete请求的模拟。它会将带有隐藏域_method的POST请求转换为put请求和delete请求提交给服务器。

过程:

springMVC笔记系列(7)——HiddenHttpMethodFilter过滤器

点击四个链接和表单按钮:

springMVC笔记系列(7)——HiddenHttpMethodFilter过滤器

springMVC笔记系列(7)——HiddenHttpMethodFilter过滤器

springMVC笔记系列(7)——HiddenHttpMethodFilter过滤器

springMVC笔记系列(7)——HiddenHttpMethodFilter过滤器

控制台输入为:

get 1
querry operations...
post 
post operations...
put 1
put operations...
delete 1
delete operations...

总结:

 Rest 风格的Url        原先利用请求参数的风格

* 以CRUD为例

* 新增: /order POST

* 修改:/order/1 Put update?id=1

* 获取:/order/1 GET get?id=1

* 删除:/order/1 DELETEdelete?id=1

* 如何发送PUT请求和DELETE请求?

 1.需要配置HiddenHttpMethodFilter

 2.需要发送POST请求

 3.需要在发送POST请求时携带一个name=”_method“的隐藏域,值为DELETE或PUT

* 在SpringMVC的目标方法中如何得到id呢?

 使用@PathVariable注解

——————————————————————————————

注意:我用的是Tomcat7服务器。tomcat8似乎不支持PUT和DELETE请求,即使我已经在Tomcat的conf文件夹下的web.xml加入了readonly参数并设置为false,依然不能解决问题。

    <servlet>
        <servlet-name>default</servlet-name>
        <servlet-class>org.apache.catalina.servlets.DefaultServlet</servlet-class>
        <init-param>
            <param-name>debug</param-name>
            <param-value>0</param-value>
        </init-param>
        
        <init-param> 
            <param-name>readonly</param-name> 
            <param-value>false</param-value> 
        </init-param> 
        
        <init-param>
            <param-name>listings</param-name>
            <param-value>false</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

点击post请求和delete请求的结果是:

springMVC笔记系列(7)——HiddenHttpMethodFilter过滤器

点赞
收藏
评论区
推荐文章
blmius blmius
2年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Karen110 Karen110
2年前
一篇文章带你了解JavaScript日期
日期对象允许您使用日期(年、月、日、小时、分钟、秒和毫秒)。一、JavaScript的日期格式一个JavaScript日期可以写为一个字符串:ThuFeb02201909:59:51GMT0800(中国标准时间)或者是一个数字:1486000791164写数字的日期,指定的毫秒数自1970年1月1日00:00:00到现在。1\.显示日期使用
Wesley13 Wesley13
2年前
java将前端的json数组字符串转换为列表
记录下在前端通过ajax提交了一个json数组的字符串,在后端如何转换为列表。前端数据转化与请求varcontracts{id:'1',name:'yanggb合同1'},{id:'2',name:'yanggb合同2'},{id:'3',name:'yang
Jacquelyn38 Jacquelyn38
2年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
Stella981 Stella981
2年前
Android So动态加载 优雅实现与原理分析
背景:漫品Android客户端集成适配转换功能(基于目标识别(So库35M)和人脸识别库(5M)),导致apk体积50M左右,为优化客户端体验,决定实现So文件动态加载.!(https://oscimg.oschina.net/oscnet/00d1ff90e4b34869664fef59e3ec3fdd20b.png)点击上方“蓝字”关注我
Stella981 Stella981
2年前
Spring MVC REST 风格的 URL
前言  本文主要内容为REST风格的URL。REST  REST(RepresentationalStateTransfer)。(资源)表现层状态转化。它是一种架构风格,用url来访问网络上的资源。  ●资源(Resources):网络上的一个实体,即网络上的一个具体的信息。比如一段文本、一张
Wesley13 Wesley13
2年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
为什么mysql不推荐使用雪花ID作为主键
作者:毛辰飞背景在mysql中设计表的时候,mysql官方推荐不要使用uuid或者不连续不重复的雪花id(long形且唯一),而是推荐连续自增的主键id,官方的推荐是auto_increment,那么为什么不建议采用uuid,使用uuid究
Python进阶者 Python进阶者
4个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这
Easter79
Easter79
Lv1
今生可爱与温柔,每一样都不能少。
文章
2.8k
粉丝
5
获赞
1.2k