Servlet过滤器大全.docx
《Servlet过滤器大全.docx》由会员分享,可在线阅读,更多相关《Servlet过滤器大全.docx(16页珍藏版)》请在冰豆网上搜索。
![Servlet过滤器大全.docx](https://file1.bdocx.com/fileroot1/2023-4/24/88610d90-ea53-4dfa-b86c-f055bedcbb39/88610d90-ea53-4dfa-b86c-f055bedcbb391.gif)
Servlet过滤器大全
Servlet过滤器大全
一、字符编码的过滤器
importjavax.servlet.*;
importjava.io.IOException;
/***//**
*用于设置HTTP请求字符编码的过滤器,通过过滤器参数encoding指明使用何种字符编码,用于处理HtmlForm请求参数的中文问题
*/
publicclassCharacterEncodingFilter
implementsFilter
{
protectedFilterConfigfilterConfig=null;
protectedStringencoding="";
publicvoiddoFilter(ServletRequestservletRequest,ServletResponseservletResponse,FilterChainfilterChain)throwsIOException,ServletException
{
if(encoding!
=null)
servletRequest.setCharacterEncoding(encoding);
filterChain.doFilter(servletRequest,servletResponse);
}
publicvoiddestroy()
{
filterConfig=null;
encoding=null;
}
publicvoidinit(FilterConfigfilterConfig)throwsServletException
{
this.filterConfig=filterConfig;
this.encoding=filterConfig.getInitParameter("encoding");
}
}
二、使浏览器不缓存页面的过滤器
importjavax.servlet.*;
importjavax.servlet.http.HttpServletResponse;
importjava.io.IOException;
/***//**
*用于的使Browser不缓存页面的过滤器
*/
publicclassForceNoCacheFilterimplementsFilter{
publicvoiddoFilter(ServletRequestrequest,ServletResponseresponse,FilterChainfilterChain)throwsIOException,ServletException
{
((HttpServletResponse)response).setHeader("Cache-Control","no-cache");
((HttpServletResponse)response).setHeader("Pragma","no-cache");
((HttpServletResponse)response).setDateHeader("Expires",-1);
filterChain.doFilter(request,response);
}
publicvoiddestroy(){
}
publicvoidinit(FilterConfigfilterConfig)throwsServletException{
}
}
三、检测用户是否登陆的过滤器
importjavax.servlet.*;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
importjavax.servlet.http.HttpSession;
importjava.util.List;
importjava.util.ArrayList;
importjava.util.StringTokenizer;
importjava.io.IOException;
/***//**
*用于检测用户是否登陆的过滤器,如果未登录,则重定向到指的登录页面
*配置参数
*checkSessionKey需检查的在Session中保存的关键字
*redirectURL如果用户未登录,则重定向到指定的页面,URL不包括ContextPath
*notCheckURLList不做检查的URL列表,以分号分开,并且URL中不包括ContextPath
*/
publicclassCheckLoginFilter
implementsFilter
{
protectedFilterConfigfilterConfig=null;
privateStringredirectURL=null;
privateListnotCheckURLList=newArrayList();
privateStringsessionKey=null;
publicvoiddoFilter(ServletRequestservletRequest,ServletResponseservletResponse,FilterChainfilterChain)throwsIOException,ServletException
{
HttpServletRequestrequest=(HttpServletRequest)servletRequest;
HttpServletResponseresponse=(HttpServletResponse)servletResponse;
HttpSessionsession=request.getSession();
if(sessionKey==null)
{
filterChain.doFilter(request,response);
return;
}
if((!
checkRequestURIIntNotFilterList(request))&&session.getAttribute(sessionKey)==null)
{
response.sendRedirect(request.getContextPath()+redirectURL);
return;
}
filterChain.doFilter(servletRequest,servletResponse);
}
publicvoiddestroy()
{
notCheckURLList.clear();
}
privatebooleancheckRequestURIIntNotFilterList(HttpServletRequestrequest)
{
Stringuri=request.getServletPath()+(request.getPathInfo()==null?
"":
request.getPathInfo());
returnnotCheckURLList.contains(uri);
}
publicvoidinit(FilterConfigfilterConfig)throwsServletException
{
this.filterConfig=filterConfig;
redirectURL=filterConfig.getInitParameter("redirectURL");
sessionKey=filterConfig.getInitParameter("checkSessionKey");
StringnotCheckURLListStr=filterConfig.getInitParameter("notCheckURLList");
if(notCheckURLListStr!
=null)
{
StringTokenizerst=newStringTokenizer(notCheckURLListStr,";");
notCheckURLList.clear();
while(st.hasMoreTokens())
{
notCheckURLList.add(st.nextToken());
}
}
}
}
四、资源保护过滤器
packagecatalog.view.util;
importjavax.servlet.Filter;
importjavax.servlet.FilterConfig;
importjavax.servlet.ServletRequest;
importjavax.servlet.ServletResponse;
importjavax.servlet.FilterChain;
importjavax.servlet.ServletException;
importjavax.servlet.http.HttpServletRequest;
importjava.io.IOException;
importjava.util.Iterator;
importjava.util.Set;
importjava.util.HashSet;
//
importmons.logging.Log;
importmons.logging.LogFactory;
/***//**
*ThisFilterclasshandlethesecurityoftheapplication.
*
*Itshouldbeconfiguredinsidetheweb.xml.
*
*@authorDerekY.Shen
*/
publicclassSecurityFilterimplementsFilter{
//theloginpageuri
privatestaticfinalStringLOGIN_PAGE_URI="login.jsf";
//theloggerobject
privateLoglogger=LogFactory.getLog(this.getClass());
//asetofrestrictedresources
privateSetrestrictedResources;
/***//**
*InitializestheFilter.
*/
publicvoidinit(FilterConfigfilterConfig)throwsServletException{
this.restrictedResources=newHashSet();
this.restrictedResources.add("/createProduct.jsf");
this.restrictedResources.add("/editProduct.jsf");
this.restrictedResources.add("/productList.jsf");
}
/***//**
*StandarddoFilterobject.
*/
publicvoiddoFilter(ServletRequestreq,ServletResponseres,FilterChainchain)
throwsIOException,ServletException{
this.logger.debug("doFilter");
StringcontextPath=((HttpServletRequest)req).getContextPath();
StringrequestUri=((HttpServletRequest)req).getRequestURI();
this.logger.debug("contextPath="+contextPath);
this.logger.debug("requestUri="+requestUri);
if(this.contains(requestUri,contextPath)&&!
this.authorize((HttpServletRequest)req)){
this.logger.debug("authorizationfailed");
((HttpServletRequest)req).getRequestDispatcher(LOGIN_PAGE_URI).forward(req,res);
}
else{
this.logger.debug("authorizationsucceeded");
chain.doFilter(req,res);
}
}
publicvoiddestroy(){}
privatebooleancontains(Stringvalue,StringcontextPath){
Iteratorite=this.restrictedResources.iterator();
while(ite.hasNext()){
StringrestrictedResource=(String)ite.next();
if((contextPath+restrictedResource).equalsIgnoreCase(value)){
returntrue;
}
}
returnfalse;
}
privatebooleanauthorize(HttpServletRequestreq){
//处理用户登录
/**//*UserBeanuser=(UserBean)req.getSession().getAttribute(BeanNames.USER_BEAN);
if(user!
=null&&user.getLoggedIn()){
//userloggedin
returntrue;
}
else{
returnfalse;
}*/
}
}
五利用Filter限制用户浏览权限
在一个系统中通常有多个权限的用户。
不同权限用户的可以浏览不同的页面。
使用Filter进行判断不仅省下了代码量,而且如果要更改的话只需要在Filter文件里动下就可以。
以下是Filter文件代码:
importjava.io.IOException;
importjavax.servlet.Filter;
importjavax.servlet.FilterChain;
importjavax.servlet.FilterConfig;
importjavax.servlet.ServletException;
importjavax.servlet.ServletRequest;
importjavax.servlet.ServletResponse;
importjavax.servlet.http.HttpServletRequest;
publicclassRightFilterimplementsFilter{
publicvoiddestroy(){
}
publicvoiddoFilter(ServletRequestsreq,ServletResponsesres,FilterChainarg2)throwsIOException,ServletException{
//获取uri地址
HttpServletRequestrequest=(HttpServletRequest)sreq;
Stringuri=request.getRequestURI();
Stringctx=request.getContextPath();
uri=uri.substring(ctx.length());
//判断admin级别网页的浏览权限
if(uri.startsWith("/admin")){
if(request.getSession().getAttribute("admin")==null){
request.setAttribute("message","您没有这个权限");
request.getRequestDispatcher("/login.jsp").forward(sreq,sres);
return;
}
}
//判断manage级别网页的浏览权限
if(uri.startsWith("/manage")){
//这里省去
}
}
//下面还可以添加其他的用户权限,省去。
}
publicvoidinit(FilterConfigarg0)throwsServletException{
}
}
--判断页面的访问权限-->
RightFilter
cn.itkui.filter.RightFilter
RightFilter
/admin/**//*
RightFilter
/manage/*
在web.xml中加入Filter的配置,如下:
EncodingAndCacheflush
EncodingAndCacheflush
encoding
UTF-8
EncodingAndCacheflush
/*
要传递参数的时候最好使用form进行传参,如果使用链接的话当中文字符的时候过滤器转码是不会起作用的,还有就是页面上
form的method也要设置为post,不然过滤器也起不了作用。
众所周知,如果没有对页面进行权限控制,用户只要输入URL就能进入任何页面。
下面就演示一下最基本的使用Fiter来控制页面的权限。
1.写一个FILTER,用来判断用户是否有权限进入指定页面。
java代码
importjava.io.IOException;
importjavax.servlet.Filter;
importjavax.servlet.FilterChain;
importjavax.servlet.FilterConfig;
importjavax.servlet.ServletException;
importjavax.servlet.ServletRequest;
importjavax.servlet.ServletResponse;
importjavax.servlet.http.HttpServlet;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
importjavax.servlet.http.HttpSession;
importorg.apache.log4j.Logger;
importcom.kiral.action.UserAction;
importcom.kiral.model.User;
/*******************************************************************************
*在过滤器中实现权限控制类,用来检验用户是否有权限进入当前页面
*
*@作者:
kiral
*@日期:
2006-6-24
*@版本:
1.0
******************************************************************************/
publicclassFilterServletextendsHttpServletimplementsFilter{
privatestaticfinallongserialVersionUID=5162189625393315379L;
privatestaticLoggerLOG=Logger.getLogger(FilterServlet.class);
/**
*配置允许的角色
*/
privateStringallowRole=null;
/**
*重定向的URL
*/
privateStringredirectURl=null;
publicvoidinit(FilterConfigfilterConfig)throwsServletException{
//得到允许的角色,这个参数是由web.xml里的allowRole所指定
allowRole=filterConfig.getInitParameter("allowRole");
//指定要重