Filter处理中文实例

过滤器类是对请求资源或则响应资源执行过滤任务,过滤器类通过doFilter方法执行过滤任务。过滤器访问FilterConfig对象,获得初始化参数。FilterConfig对象是一个servletContext的引用,用它可以导入过滤任务需要的初始化参数。

 

代码:

EncodingFilter.java

 

package com.test;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class EncodingFilter implements Filter {

	String encoding = null;
	FilterConfig filterConfig = null;
	
	//初始化方法
	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub
		this.filterConfig = filterConfig;
		this.encoding = filterConfig.getInitParameter("encoding");
	}

	//过滤处理方法
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		if (encoding!=null){
			//对请求进行编码设置
			request.setCharacterEncoding(encoding);
		}
		//将处理权转交给下一个处理器
		chain.doFilter(request,response);
	}

	//销毁方法
	public void destroy() {
		// TODO Auto-generated method stub
		this.encoding = null;
		this.filterConfig = null;
	}

}


index.htm

 

<html>
  <head>
    <title>编码过滤器测试</title>
    <meta http-equiv="content-type" content="text/html; charset=gb2312">
  </head>
  
  <body>
    <form name="form1" action="process.jsp" method="POST">
    	请输入姓名:<input name="name" type="text">
    	<input name="submit" value="提交" type="submit">
    </form>
  </body>
</html>


 

process.jsp

 

<%@ page language="java" import="java.util.*" pageEncoding="gb2312"%>
<html>
  <head>
    <title>编码过滤器测试</title>
  </head>
  
  <body>
    <%=request.getParameter("name")%>,你好!<br>
  </body>
</html>


 

web.xml

 

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" 
	xmlns="http://java.sun.com/xml/ns/j2ee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
	http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
	
	<filter>
		<filter-name>encodingFilter</filter-name>
		<filter-class>com.test.EncodingFilter</filter-class>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>gb2312</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>encodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

</web-app>


 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值