SpringMVC框架

3.3 HiddenHttpMethodFilter过滤器源码分析

  • 为什么请求隐含参数名称必须叫做”_method”
  • hiddenHttpMethodFilter 的处理过程

 

3.4 实验代码

  • 配置HiddenHttpMethodFilter过滤器

<!-- 支持REST风格的过滤器:可以将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>

  • 代码

/**

 * 1.测试REST风格的  GET,POST,PUT,DELETE 操作

 * 以CRUD为例:

 * 新增: /order POST

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

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

 * 删除: /order/1 DELETE        delete?id=1

 

 * 2.如何发送PUT请求或DELETE请求?

 * ①.配置HiddenHttpMethodFilter

 * ②.需要发送POST请求

 * ③.需要在发送POST请求时携带一个 name="_method"的隐含域,值为PUT或DELETE

 

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

 *   使用@PathVariable注解

 */

@RequestMapping(value="/testRESTGet/{id}",method=RequestMethod.GET)

public String testRESTGet(@PathVariable(value="id") Integer id){

System.out.println("testRESTGet id="+id);

return "success";

}

 

@RequestMapping(value="/testRESTPost",method=RequestMethod.POST)

public String testRESTPost(){

System.out.println("testRESTPost");

return "success";

}

 

@RequestMapping(value="/testRESTPut/{id}",method=RequestMethod.PUT)

public String testRESTPut(@PathVariable("id") Integer id){

System.out.println("testRESTPut id="+id);

return "success";

}

 

@RequestMapping(value="/testRESTDelete/{id}",method=RequestMethod.DELETE)

public String testRESTDelete(@PathVariable("id") Integer id){

System.out.println("testRESTDelete id="+id);

return "success";

}