springmvc的过滤器--Filter

一、CharacterEncodingFilter:POST中文乱码解决方案

spring Web MVC框架提供了org.springframework.web.filter.CharacterEncodingFilter用于解决POST方式造成的中文乱码问题,具体配置如下:

 

java代码:
Java代码  收藏代码
  1.   
  2.     CharacterEncodingFilter  
  3.     class>org.springframework.web.filter.CharacterEncodingFilterclass>  
  4.       
  5.         encoding  
  6.         utf-8  
  7.       
  8.   
  9.   
  10.     CharacterEncodingFilter  
  11.     /*  
  12.   

 


二、HiddenHttpMethodFilter

 浏览器 form 单只支持 GET 与 POST 请求,DELETE、PUT method 并不支持 

Spring3.0 添加了一个过滤器可以将 这些请求转换为标准 http 方法使得 支持 GET、POST、PUT 与DELETE 请求。


以下是实例

1、在web.xml中配置HiddenHttpMethodFilter


	
		HiddenHttpMethodFilter
		org.springframework.web.filter.HiddenHttpMethodFilter
	
	
	
		HiddenHttpMethodFilter
		/*
	

2、编写页面控制器类

package com.atguigu.springmvc;

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("/springmvc")
@Controller
public class SpringMVCTest {
	
	@RequestMapping(value="testRest/{id}",method=RequestMethod.GET)
	public String testGet(@PathVariable(value="id") Integer id) {
		System.out.println("get" + id);
		return "success";
	}
	
	@RequestMapping(value="testRest",method=RequestMethod.POST)
	public String testPost() {
		System.out.println("Post");
		return "success";
	}

	@RequestMapping(value="testRest/{id}", method=RequestMethod.PUT)
	public String testPut(@PathVariable(value="id") Integer id) {
		System.out.println("Put" +id);
		return "success";
	}
	
	@RequestMapping(value="/testRest/{id}", method=RequestMethod.DELETE)
	public String delete(@PathVariable(value="id") Integer id) {
		
		System.out.println("delete" + id);
		return "success";
	}
	
}

注解解析:

 1. @RequestMapping: 除了修饰方法, 还可来修饰类 

 1). 类定义处: 提供初步的请求映射信息。相对于 WEB 应用的根目录
 2). 方法处: 提供进一步的细分映射信息。 相对于类定义处的 URL。

若类定义处未标注 @RequestMapping,则方法处标记的 URL相对于 WEB 应用的根目录
3)使用 method 属性来指定请求方式 

另外:还可以使用 params 和 headers 来更加精确的映射请求. params 和 headers 支持简单的表达式.(一般 不用)

2.@PathVariable :可以来映射 URL 中的占位符到目标方法的参数中.。value属性的值要和占位符名称一致。

3、编写jsp页面,用于通过超链接发送请求


	






Test Rest Get

总结:

表单只支持post请求和get请求,那如何通过表单发送put请求和delete请求呢?

1、需要在web.xml中配置HiddenHttpMethodFilter

2、需要在表单中发送Post请求

3、需要在表单发送Post请求时携带一个name="_method"的隐藏域,value可取 delete 或 put。


你可能感兴趣的:(springmvc)