本篇文章是介绍javax.servlet包中Filter的几个功能,一是字符编码过滤,二是拦截指文件夹中的文件,实现登录验证.实现以上两个功能需以下几个步骤:
1、实现javax.servlet.Filter接口,编写两个类,如下:
/**
* 作用:过滤编码
*/
package filter;
import java.io.IOException;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
public class EncodingFilter implements Filter
{
protected FilterConfig filterConfig;
private String targetEncoding;
public EncodingFilter()
{
targetEncoding = "gb2312";//直接初始化0912
}
public void init(FilterConfig filterconfig) throws ServletException
{
filterConfig = filterconfig;
//targetEncoding = filterconfig.getInitParameter("encoding");//web.xml挂参初始化
}
public void doFilter(ServletRequest servletrequest, ServletResponse servletresponse, FilterChain filterchain)
throws IOException, ServletException
{
HttpServletRequest httpservletrequest = (HttpServletRequest)servletrequest;
httpservletrequest.setCharacterEncoding(targetEncoding);
System.out.println("使用" targetEncoding "对请求进行编码过滤");
filterchain.doFilter(servletrequest, servletresponse);
}
public void setFilterConfig(FilterConfig filterconfig)
{
filterConfig = filterconfig;
}
public void destroy()
{
filterConfig = null;
}
}
/**
* 作用:过滤外界非法的进入页面
* 注意:使用该功能时,一定要把登录页与被过滤文件夹设为同级,否则会出现循环
*/
package filter;
import java.io.IOException;
import javax.servlet.*;
import javax.servlet.http.*;
public class ManageFilter implements Filter
{
String LOGIN_PAGE;
protected FilterConfig filterConfig;
public ManageFilter()
{
LOGIN_PAGE = "/login.jsp";
}
public void doFilter(ServletRequest servletrequest, ServletResponse servletresponse, FilterChain filterchain)
throws IOException, ServletException
{
HttpServletRequest request = (HttpServletRequest) servletrequest;
HttpServletResponse response = (HttpServletResponse) servletresponse;
HttpSession session = request.getSession();
String key = "";
try
{
//通过验证时在session中存的一个标志
key = (String) session.getAttribute("key");
if (key!= null&&key.equals("ok"))
{
filterchain.doFilter(servletrequest, servletresponse);
}
else
{
response.sendRedirect(LOGIN_PAGE);
System.out.println("被拦截一个未认证的请求");
}
}
catch (Exception exception)
{
exception.printStackTrace();
}
}
public void setFilterConfig(FilterConfig filterconfig)
{
filterConfig = filterconfig;
}
public void destroy()
{
filterConfig = null;
}
public void init(FilterConfig filterconfig)
throws ServletException
{
filterConfig = filterconfig;
}
}
2、在web.xml中做一些设置
<filter>
<filter-name>code</filter-name>
<filter-class>filter.EncodingFilter</filter-class>
</filter>
<filter>
<filter-name>manage</filter-name>
<filter-class>filter.ManageFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>code</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>manage</filter-name>
<!-- <url-pattern>/ShuiBaoRHPWK_NEW/system/ruhepaiwukou/*</url-pattern>-->
<url-pattern>/servlets-examples/*</url-pattern>
</filter-mapping>
OK,基本FILTER应该做的基本就这样,你只需要在程序中验证通过时,在session中存个标志进去,好让ManageFilter可以找到,就可以了!