加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

web.xml中配置过滤器

(2014-01-09 18:09:35)
标签:

it

分类: Java

下面是该Filter的源代码。

程序清单:codes/02/2.12/ filterTest/WEB-INF/src/lee/AuthorityFilter.java

public class AuthorityFilter implements Filter 
{
//FilterConfig可用于访问Filter的配置信息
private FilterConfig config;
//实现初始化方法
public void init(FilterConfig config)
{
this.config = config;
}
//实现销毁方法
public void destroy()
{
this.config = null;
}
//执行过滤的核心方法
public void doFilter(ServletRequest request,
ServletResponse response, FilterChain chain)
throws IOException,ServletException
{
//获取该Filter的配置参数
String encoding = config.getInitParameter("encoding");
String loginPage = config.getInitParameter("loginPage");
String proLogin = config.getInitParameter("proLogin");
//设置request编码用的字符集
request.setCharacterEncoding(encoding); //①
HttpServletRequest requ = (HttpServletRequest)request;
HttpSession session = requ.getSession(true);
//获取客户请求的页面
String requestPath = requ.getServletPath();
//如果session范围的user为null,即表明没有登录
//且用户请求的既不是登录页面,也不是处理登录的页面
if( session.getAttribute("user") == null
&& !requestPath.endsWith(loginPage)
&& !requestPath.endsWith(proLogin))
{
//forward到登录页面
request.setAttribute("tip" , "您还没有登录");
request.getRequestDispatcher(loginPage)
.forward(request, response);
}
//“放行”请求
else
{
chain.doFilter(request, response);
}
}
}

上面Filter的doFilter方法里3行斜体字代码用于获取Filter的配置参数,而程序中粗体字代码则是此Filter的核心,①号代码按配置参数设置了request编码所用的字符集,接下来的粗体字代码判断session范围内是否有user属性——没有该属性即认为没有登录,如果既没有登录,而且请求地址也不是登录页和处理登录页,系统直接跳转到登录页面。

在web.xml文件中配置该Filter,使用init-param元素为该Filter配置参数,init-param可接受如下两个子元素:

param-name:指定参数名。

param-value:指定参数值

http://s5/mw690/001KyrLCgy6FEQKrGba64&690




authority

lee.AuthorityFilter


encoding
GBK


loginPage
/login.jsp


proLogin
/proLogin.jsp





authority

/*

上面配置片段中粗体字代码为该Filter指定了3个配置参数,指定loginPage为/login.jsp,proLogin为/proLogin.jsp,这表明:如果没有登录该应用,普通用户只能访问/login.jsp和/proLogin.jsp页面。只有当用户登录该应用后才可自由访问其他页面。

0

阅读 收藏 喜欢 打印举报/Report
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有