filter的用法,的确是比较有扩展性的一种方法...可以通过filter结合读取web.xml中的filter参数来完成一系列的动作,做法如下:
首先,实现javax.servlet.Filter接口,编写一个处理request编码的过滤器类...
package tutorial.struts.filter;
import javax.servlet.Filter;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.FilterChain;
import java.io.IOException;
public class SetCharacterEncodingFilter implements Filter {
protected FilterConfig filterConfig;
protected String encodingName;
protected boolean enable;
public SetCharacterEncodingFilter() {
this.encodingName = "UTF-8";
this.enable = false;
}
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
loadConfigParams();
}
private void loadConfigParams()
{
//encoding
this.encodingName = this.filterConfig.getInitParameter("encoding");
//filter enable flag...
String strIgnoreFlag = this.filterConfig.getInitParameter("enable");
if (strIgnoreFlag.equalsIgnoreCase("true"))
{
this.enable = true;
}
else
{
this.enable = false;
}
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException
{
if(this.enable)
{
request.setCharacterEncoding(this.encodingName);
}
chain.doFilter(request, response);
}
public void destroy()
{
}
}
然后,需要在web.xml中注册我们的过滤器类:
<filter>
<filter-name>Set Character Encoding</filter-name>
<filter-class>tutorial.struts.filter.SetCharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>enable</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>Set Character Encoding</filter-name>
<servlet-name>Action Servlet</servlet-name>
</filter-mapping>
<filter-mapping>
<filter-name>Set Character Encoding</filter-name>
<servlet-name>Faces Servlet</servlet-name>
</filter-mapping>
这样,任何通过Struts,或是JSF的Controller Servlet处理的request,都会在过滤器中先行处理,才把控制权交还给Struts或是JSF,而且Filter中有一个Process Chain的概念,是一个很吸引人的东东~~!