Filter:过滤器,下图是Filter在Model1中的执行流程,通过Filter我们可以统一设置字符集,而不用在每一个JSP页面中手动设置字符集,这样做的目的很简单,降低耦合性.有了Filter的面向切面编程,我们可以把Filter直接插入到Model1的执行流程.
<%@ page language="java" contentType="text/html; charset=GB18030"
pageEncoding="GB18030"%>
Filter功能介绍
使用户可以改变一个request和修改一个response,Filter不是一个servlet,它不能产生一个response,它能够在一个request到达servlet之前预处理request,也可以在response离开servlet时处理response,换种说法,filter其实是一个servlet chaining(servlet链)
Filter方法
1. void setFilterConfig(FilterConfig config) //设置filter 的配置对象;
2. FilterConfig getFilterConfig() //返回filter的配置对象;
3. void doFilter(ServletRequest req,ServletResponse res,FilterChain chain) //执行filter 的工作
编写一个CharsetEncodingFilter类,必须要实现javax.servlet类
//这是一个自己写的CharsetEncodingFilter类
package com.bjpowernode.drp.filter;
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 CharsetEncodingFilter implements Filter {
private String endcoding;
public void destroy() {
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
//设置字符集
request.setCharacterEncoding("GB18030");
//继续执行
chain.doFilter(request,response);
}
public void init(FilterConfig filterConfig) throws ServletException {
this.endcoding=filterConfig.getInitParameter("encoding");
}
}
如果要运行这个CharsetEncodingFilter ,必须要配置web.xml,以tomcat5.0为例
<?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>CharsetEncodingFilter</filter-name>
<filter-class>com.bjpowernode.drp.filter.CharsetEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>GBK</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharsetEncodingFilter</filter-name>
<url-pattern>*.jsp</url-pattern>
</filter-mapping>
</web-app>