博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Servlet过滤器介绍之原理分析
阅读量:6330 次
发布时间:2019-06-22

本文共 8685 字,大约阅读时间需要 28 分钟。

1
Servlet
过滤器
1.1 
什么是过滤器
过滤器是一个程序,它先于与之相关的servlet
JSP
页面运行在服务器上。过滤器可附加到一个或多个servlet
JSP
页面上,并且可以检查进入这些资源的请求信息。在这之后,过滤器可以作如下的选择:
①以常规的方式调用资源(即,调用servlet
JSP
页面)。
②利用修改过的请求信息调用资源。
③调用资源,但在发送响应到客户机前对其进行修改。
④阻止该资源调用,代之以转到其他的资源,返回一个特定的状态代码或生成替换输出。
 
1.2 Servlet
过滤器的基本原理
Servlet
作为过滤器使用时,它可以对客户的请求进行处理。处理完成后,它会交给下一个过滤器处理,这样,客户的请求在过滤链里逐个处理,直到请求发送到目标为止。例如,某网站里有提交“修改的注册信息”的网页,当用户填写完修改信息并提交后,服务器在进行处理时需要做两项工作:判断客户端的会话是否有效;对提交的数据进行统一编码。这两项工作可以在由两个过滤器组成的过滤链里进行处理。当过滤器处理成功后,把提交的数据发送到最终目标;如果过滤器处理不成功,将把视图派发到指定的错误页面。
2
Servlet
过滤器开发步骤
开发Servlet
过滤器的步骤如下:
①编写实现Filter
接口的Servlet
类。
②在web.xml
中配置Filter
开发一个过滤器需要实现Filter
接口,Filter
接口定义了以下方法:
destory
()由Web
容器调用,初始化此Filter
init
FilterConfig filterConfig
)由Web
容器调用,初始化此Filter
doFilter
ServletRequest request,ServletResponse response,FilterChain chain
)具体过滤处理代码。
3
.一个过滤器框架实例
SimpleFilter1.java
package
 com.zj.sample;
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
 SimpleFilter1 
implements
 Filter {
    
@SuppressWarnings
(
"unused"
)
    
private
 FilterConfig 
filterConfig
;
 
    
public
 
void
 init(FilterConfig config) 
throws
 ServletException {
       
this
.
filterConfig
 = config;
    }
 
    
public
 
void
 doFilter(ServletRequest request, ServletResponse response,
           FilterChain chain) {
       
try
 {
           System.
out
.println(
"Within SimpleFilter1:Filtering the Request..."
);
           chain.doFilter(request, response);
// 
把处理发送到下一个过滤器
           System.
out
 .println(
"Within SimpleFilter1:Filtering the Response..."
);
       
catch
 (IOException ioe) {
           ioe.printStackTrace();
       
catch
 (ServletException se) {
           se.printStackTrace();
       }
    }
 
    
public
 
void
 destroy() {
       
this
.
filterConfig
 = 
null
;
    }
}
 
SimpleFilter2.java
package
 com.zj.sample;
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
 SimpleFilter2 
implements
 Filter {
    
@SuppressWarnings
(
"unused"
)
    
private
 FilterConfig 
filterConfig
;
 
    
public
 
void
 init(FilterConfig config) 
throws
 ServletException {
       
this
.
filterConfig
 = config;
    }
 
    
public
 
void
 doFilter(ServletRequest request, ServletResponse response,
           FilterChain chain) {
       
try
 {
           System.
out
.println(
"Within SimpleFilter2:Filtering the Request..."
);
           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() {
       
this
.
filterConfig
 = 
null
;
    }
}
 
web.xml
<
filter
>
    
<
filter-name
>
filter1
</
filter-name
>
    
<
filter-class
>
com.zj.sample.SimpleFilter1
</
filter-class
>
</
filter
>
<
filter-mapping
>
    
<
filter-name
>
filter1
</
filter-name
>
    
<
url-pattern
>
/*
</
url-pattern
>
//
为所有的访问做过滤
</
filter-mapping
>
 
<
filter
>
    
<
filter-name
>
filter2
</
filter-name
>
    
<
filter-class
>
com.zj.sample.SimpleFilter2
</
filter-class
>
</
filter
>
<
filter-mapping
>
    
<
filter-name
>
filter2
</
filter-name
>
    
<
url-pattern
>
/*
</
url-pattern
>
//
为所有的访问做过滤
</
filter-mapping
>
 
打开web
容器中任意页面输出结果:
(注意过滤器执行的请求/
响应顺序)
Within SimpleFilter1:Filtering the Request...

Within SimpleFilter2:Filtering the Request...

Within SimpleFilter2:Filtering the Response...

Within SimpleFilter1:Filtering the Response...

4
.报告过滤器
我们来试验一个简单的过滤器,只要调用相关的servlet
JSP
页面,它就打印一条消息到标准输出。为实现此功能,在doFilter
方法中执行过滤行为。每当调用与这个过滤器相关的servlet
JSP
页面时,doFilter
方法就生成一个打印输出,此输出列出请求主机和调用的URL
。因为getRequestURL
方法位于HttpServletRequest
而不是ServletRequest
中,所以把ServletRequest
对象构造为HttpServletRequest
类型。我们改动一下章节3
SimpleFilter1.java
SimpleFilter1.java
package
 com.zj.sample;
import
 java.io.IOException;
import
 java.util.Date;
import
 javax.servlet.Filter;
import
 javax.servlet.FilterChain;
import
 javax.servlet.FilterConfig;
import
 javax.servlet.ServletException;
import
 javax.servlet.ServletRequest;
import
 javax.servlet.ServletResponse;
import
 javax.servlet.http.HttpServletRequest;
 
public
 
class
 SimpleFilter1 
implements
 Filter {
    
@SuppressWarnings
(
"unused"
)
    
private
 FilterConfig 
filterConfig
;
 
    
public
 
void
 init(FilterConfig config) 
throws
 ServletException {
       
this
.
filterConfig
 = config;
    }
 
    
public
 
void
 doFilter(ServletRequest request, ServletResponse response,
           FilterChain chain) {
       
try
 {
           System.
out
.println(
"Within SimpleFilter1:Filtering the Request..."
);
           HttpServletRequest req = (HttpServletRequest) request;
           System.
out
.println(req.getRemoteHost() + 
" tried to access "
                  + req.getRequestURL() + 
" on "
 + 
new
 Date() + 
"."
);
           chain.doFilter(request, response);
           System.
out
.println(
"Within SimpleFilter1:Filtering the Response..."
);
       
catch
 (IOException ioe) {
           ioe.printStackTrace();
       
catch
 (ServletException se) {
           se.printStackTrace();
       }
    }
 
    
public
 
void
 destroy() {
       
this
.
filterConfig
 = 
null
;
    }
}
 
web.xml
设置不变,同章节3
 
测试:
输入[url]http://localhost:8080/Test4Jsp/login.jsp[/url]
 
结果:
Within SimpleFilter1:Filtering the Request...

0:0:0:0:0:0:0:1 tried to access [url]http://localhost:8080/Test4Jsp/login.jsp[/url] on Sun Mar 04 17:01:37 CST 2007.

Within SimpleFilter2:Filtering the Request...

Within SimpleFilter2:Filtering the Response...

Within SimpleFilter1:Filtering the Response...

5
.访问时的过滤器
(在过滤器中使用servlet
初始化参数)
下面利用init
设定一个正常访问时间范围,对那些不在此时间段的访问作出记录。我们改动一下章节3
SimpleFilter2.java
SimpleFilter2
.java
package
 com.zj.sample;
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.xml
           
endTime
 = 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));
       }
    }
}
 
web.xml
设置不变。
关于Tomcat
日志处理,这里补充介绍一下。config.getServletContext().log
"log message"
)会将日志信息写入<CATALINA_HOME>/logs
文件夹下,文件名应该为localhost_log.2007-03-04.txt
这样的形式(按日期每天产生一个,第二天可以看见)。要得到这样一个日志文件,应该在server.xml
中有:
<Logger className="org.apache.catalina.logger.FileLogger" prefix="catalina_log." suffix=".txt" timestamp="true"/>
本文转自zhangjunhd51CTO博客,原文链接:http://blog.51cto.com/zhangjunhd/20629,如需转载请自行联系原作者
你可能感兴趣的文章
[转]mysql使用关键字作为列名的处理方式
查看>>
awesome go library 库,推荐使用的golang库
查看>>
树形展示形式的论坛
查看>>
jdbcTemplate 调用存储过程。 入参 array 返回 cursor
查看>>
C++中的stack类、QT中的QStack类
查看>>
Linux常用基本命令[cp]
查看>>
CSS 相对|绝对(relative/absolute)定位系列(一)
查看>>
关于 Nginx 配置 WebSocket 400 问题
查看>>
Glide和Govendor安装和使用
查看>>
Java全角、半角字符的关系以及转换
查看>>
Dubbo和Zookeeper
查看>>
前端项目课程3 jquery1.8.3到1.11.1有了哪些新改变
查看>>
UOJ#179. 线性规划(线性规划)
查看>>
整合spring cloud云架构 - SSO单点登录之OAuth2.0登录认证(1)
查看>>
Isolation Forest原理总结
查看>>
windows的服务中的登录身份本地系统账户、本地服务账户和网络服务账户修改
查看>>
JAVA中循环删除list中元素的方法总结
查看>>
redis 安装
查看>>
C# tips ---值类型的装箱和拆箱
查看>>
SQL some any all
查看>>