servlet过滤器
一.过滤器作用
- 用户认证与授权管理,统计web应用访问量(找到就访问,没的话转到其他页面)和访问命中率和形成访问报告。
- 实现web应用的日志处理功能
- 实现数据压缩和加密功能
- 实现xml和xstl的转换。
二.预备知识
- init() :这个方法在容器实例化过滤器时被调用,它主要设计用于使过滤器为处理做准备。该方法接受一个 FilterConfig 类型的对象作为输入。
- doFilter() :与 servlet 拥有一个 service() 方法(这个方法又调用 doPost() 或者 doGet() )来处理请求一样,过滤器拥有单个用于处理请求和响应的方法?D?D doFilter() 。这个方法接受三个输入参数:一个 ServletRequest 、 response 和一个 FilterChain (可能多个filter,按顺序执行)对象。 这里的ServletRequest和ServletResponse一般需要转换成具体的Servlet实现对于的对象,如:HttpServletRequest和HttpServletResponse。
doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
- destroy() :正如您想像的那样,这个方法执行任何清理操作,这些操作可能需要在自动垃圾收集之前进行。当Servlet容器在销毁过滤器实例前,该方法销毁过滤器占用的资源。
三.代码
1.访问时间限制
//访问时的过滤器(在过滤器中使用servlet初始化参数)
//下面利用init设定一个正常访问时间范围,对那些不在此时间段的访问作出记录
import java.io.IOException;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
public class SimpleFilter2 implements Filter {@SuppressWarnings("unused")
private FilterConfig config;
private ServletContext context;
private int startTime, endTime;private DateFormat formatter;
public void init(FilterConfig config) throws ServletException {this.config = config;
context = config.getServletContext();formatter = DateFormat.getDateTimeInstance(DateFormat.MEDIUM,DateFormat.MEDIUM);try {
startTime = Integer.parseInt(config.getInitParameter("startTime"));// web.xmlendTime = Integer.parseInt(config.getInitParameter("endTime"));// web.xml} catch (NumberFormatException nfe) { // Malformed or null// Default: access at or after 10 p.m. but before 6 a.m. is
// considered unusual.
startTime = 22; // 10:00 p.m.
endTime = 6; // 6:00 a.m.
}}public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) {try {
System.out.println("Within SimpleFilter2:Filtering the Request...");
HttpServletRequest req = (HttpServletRequest) request;GregorianCalendar calendar = new GregorianCalendar();
int currentTime = calendar.get(Calendar.HOUR_OF_DAY);
if (isUnusualTime(currentTime, startTime, endTime)) {
context.log("WARNING: " + req.getRemoteHost() + " accessed "+ req.getRequestURL() + " on "
+ formatter.format(calendar.getTime()));// The log file is under <CATALINA_HOME>/logs.One log per day.
}chain.doFilter(request, response);System.out.println("Within SimpleFilter2:Filtering the Response...");
} catch (IOException ioe) {
ioe.printStackTrace();} catch (ServletException se) {
se.printStackTrace();}}public void destroy() {}// Is the current time between the start and end
// times that are marked as abnormal access times?
private boolean isUnusualTime(int currentTime, int startTime, int endTime) {// If the start time is less than the end time (i.e.,
// they are two times on the same day), then the
// current time is considered unusual if it is
// between the start and end times.
if (startTime < endTime) {
return ((currentTime >= startTime) && (currentTime < endTime));
}// If the start time is greater than or equal to the
// end time (i.e., the start time is on one day and
// the end time is on the next day), then the current
// time is considered unusual if it is NOT between
// the end and start times.
else {
return (!isUnusualTime(currentTime, endTime, startTime));
}}}
参考资料:http://zhangjunhd.blog.51cto.com/113473/20629
2.登陆限制
public class LoginFilter implements Filter {@Overridepublic void init(FilterConfig filterConfig) throws ServletException {System.out.println("init LoginFilter");
}@Overridepublic void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException {
//把ServletRequest和ServletResponse转换成真正的类型
HttpServletRequest req = (HttpServletRequest)request;HttpSession session = req.getSession();//由于web.xml中设置Filter过滤全部请求,可以排除不需要过滤的url
String requestURI = req.getRequestURI();if(requestURI.endsWith("login.jsp")){chain.doFilter(request, response);return;
}//判断用户是否登录,进行页面的处理
if(null == session.getAttribute("user")){//未登录用户,重定向到登录页面
((HttpServletResponse)response).sendRedirect("login.jsp");
return;
} else {
//已登录用户,允许访问
chain.doFilter(request, response);}}@Overridepublic void destroy() {System.out.println("destroy!!!");
}}
3.过滤敏感词
public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException {
//转换成实例的请求和响应对象
HttpServletRequest req = (HttpServletRequest)request;HttpServletResponse resp = (HttpServletResponse)response;//获取评论并屏蔽关键字
String comment = req.getParameter("comment");
comment = comment.replace("A", "***");//重新设置参数
req.setAttribute("comment", comment);
//继续执行
chain.doFilter(request, response);}
作者:火星十一郎
本文版权归作者火星十一郎所有,欢迎转载和商用,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利.