javax.servlet.filter的用法
如何实现一个过滤器呢?
1.所在的类实现Filter接口
public interface Filter
public void init(FilterConfig filterConfig)throws
ServletException过滤器初始化是在容器启动时自动初始化
public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain)throws
IOException,ServletExcepton
在标准Servlet中的doGet或doPost 方法中,传递参数为:HttpServletRequest、HttpServletResponse
过滤器销毁
public void destroy()
package cn.mldn.lxh.filter
import java.io.*;
import javax.servlet.*;
public class FirstFilter implements Filter
{
public void init(FilterConfig config)throws ServletException
{
System.out.println("过滤器初始化");
}
public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain) throws IOException,ServletException
{
System.out.println(过滤doFilter);
}
public void destroy()
{
System.out.println(过滤器销毁);
}
}
web.xml文件配置
<filter>
<filter-name>first</filter-name>
<filter-class>cn.mldn.lxh.filter.FirstFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>first</filter-name>
与servlet中的url-pattern不一样,此处表示对那个页面进行过滤,如果全部都过滤,则"/*"
<url-pattern>/*</url-pattern>
</filter-mapping>
如果过滤器要将内容传递到目的地,则需要FilterChain,将请求继续向下转发
过滤器也会执行两次:FilterChain这前执行一次,之后再执行一次
1.过滤非法文字:
package cn.mldn.lxh.filter;
import java.io.*;
import javax.servlet.*;
public class CharFilter implements Filter
{
public void init(FilterConfig filterConfig)throws ServletException
{
//System.out.println("init");
}
public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain)throws IOException,ServletException
{
String content=request.getParameter("content");
//如果indexOf返回-1则表示没有查到所要的内容
if(content!=null)
if(content.indexOf("AAA")==-1)
{
chain.doFilter(request,response);
}
esle
{
System.out.println("有非法文字");
//如果需要的话,此处依然可以使用RequestDispatcher进行跳转
}
}
else
{
chain.doFilter(request,response);
}
}
public void destroy()
{
//System.out.println("过滤器销毁");
}
<filter>
<filter-name>char</filter-name>
<filter-class>cn.mldn.lxh.filter.CharFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>char</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
2.对内容进行统一的编码
setCharacterEncoding("GB2312");
package cn.mldn.lxh.filter;
import java.io.*;
import javax.servlet.*;
public class EncodingFilter implements Filter
{
public void init(FilterConfig filterConfig)throws ServletException
{
//System.out.println("过滤器初始化");
}
public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain)throws IOException,ServletException
{
try{
request.setCharacterEncoding("GB2312");
}
catch(Exception e)
{}
chain.doFilter(request,response);
}
public void destroy()
{
//System.out.println("销毁");
}
}
<filter>
<filter-name>encoding</filter-name>
<filter-class></filter-class>
</filter>
<filter-mapping>
<filter-name>encoding</filter-name>
<url-pattern