Java过滤器的使用与拦截排除的实现
本文就以下几个内容进行说明和说明。
web.xml简要介绍
过滤器的工作原理
过滤器的实现
拦截的实现和说明
web.xml简要介绍
在Java开发中,我们每天都与拦截器进行交流,但很多人可能并不深刻理解filter是什么。 我也不知道web.xml中的servlet、servlet-mapping、filter和filter-mapping,所以现在很容易做到
servlet
a
com.test.TestServlet
a
/a.do
在servlet中,声明名称为a的servlet,表示相应的实现类com.test.TestServlet。 servlet-mapping表示在发送请求后缀为a.do的http请求后,该请求调用名为a的servlet,换句话说,通过运行TestServlet来处理请求。
菲尔斯特
如果有上面servlet的理解,我们了解filter会更方便。 请参阅以下简单配置。
会话过滤器
com.demo.test.util.session filter
已排除页面
/index.jsp
会话过滤器
/index.jsp
上面的过滤器表示声明一个名为SessionFilter的过滤器,该过滤器的具体实现对应于com.demo.test.util.session filter。 此筛选器具有与在httpServletRequest对象中声明的请求参数相同的初始化参数(名称: excludedPages,参数: excludedPages )。 filter-mapping意味着在系统上出现访问index.jsp的http请求时调用拦截器,即运行com.demo.test.util.session filter 如果想深入了解过滤器的工作原理,自己搜索资料就可以了,还有很多资料。
过滤器的具体class实现
publicclasssessionfilterimplementsfilter {
私有字符串封装页;
privatestring [ ] excludedpagearray;
/* * * @ see过滤器# destroy () /
公共语音目录
返回;
}
publicvoiddofilter (servletrequestrequest,servlet响应响应,
filterchainchain (throwsioexception,ServletException { )。
布尔型isexcludedpage=false;
for (字符串页面: Excludedpagearray ) {
if () (httpservletrequest ) request (.get servlet path ) ).equals (page ) ) {
isExcludedPage=true;
布雷克;
}
}
if(isexcludedpage ) {
chain.dofilter(request,response );
(else )//
http session session=(http servlet request ) request ).getSession );
if (session==null|| session.getattribute (' ' )==null ) {
(HttpServletResponse ) response ).sendredirect ) (/login.htm );
} else {
chain.dofilter(request,response );
}
}
}
公共语音识别初始化(filterconfigfconfig ) throws ServletException { )。
excluded pages=fconfig.getinitparameter (excluded pages );
if (空!=excludedpagesexcludedpages.length {
excludedpagearray=excluded pages.split (,);
}
返回;
}
}
运行拦截器时,首先执行init方法。 init方法可以获取在web.xml中设置为filter的初始化参数。 如果要执行init方法,请执行dofilter方法。 该方法实现了过滤器的拦截作用,实现了拦截排除。
拦截器的工作原理是如何实现拦截器的:
http请求到达后,如果符合web.xml中的filter-mapping映射规则,则触发filter的执行,如果不监听,则调用chain.dofilter(request,response )
排除实现拦截,对某个要求如何不拦截:
在一个请求到达后,我们在init上获取了web.xml中为filter设置的初始化参数。 获取此初始化数据是不请求拦截的规则,本示例使用index.jsp作为拦截排除请求。 使用index.jsp作为过滤器来触发映射条件。 也就是说,当系统中的http请求以index.jsp结尾时,该请求将触发SessionFilter的运行。 在SessionFilter中,排除拦截的参数是index.jsp。 if () (httpservletrequest ) request ).getServletPath ).equals )代码处理当前请求是否为请求index.jsp,否则不会阻止可以通过在filter中创建初始化参数,并在filter中将当前请求与初始化参数进行比较,来判断是否监听此次请求。 如果阅读时遇到问题,可以自己搜索资料,详细说明web.xml在Javaweb项目中的作用。