Java web servlet 拦截器 以登陆为例子

以登陆为例子...............

public class LoginFilter implements Filter {

@Override
public void destroy() {

}

@Override
public void init(FilterConfig arg0) throws ServletException {

}

@Override
public void doFilter(ServletRequest arg0, ServletResponse arg1,FilterChain arg2)
throws IOException, ServletException {

HttpServletResponse response = (HttpServletResponse) arg1;
HttpServletRequest request=(HttpServletRequest)arg0;
HttpSession session = request.getSession(true);
String loginName = (String) session.getAttribute("loginName");//
String url=request.getRequestURI();
if(loginName==null || loginName.equals(""))
{
//判断获取的路径不为空且不是访问登录页面或执行登录操作时跳转
if(url!=null && !url.equals("") && ( url.indexOf("Login")<0 && url.indexOf("login")<0 ))
{
response.sendRedirect("login.jsp");
return ;
}
}
//已通过验证,用户访问继续
arg2.doFilter(arg0, arg1);
}

}

-----------------------------------------------------------------------------------------------------------

web.xml

<!-- 拦截 -->
<filter>
<filter-name>LoginFilter</filter-name>
<filter-class>onlyfun.filter.LoginFilter</filter-class>
</filter>

<!-- 配置多个映射,哪些请求执行过滤器 -->
<filter-mapping>
<filter-name>LoginFilter</filter-name>
<url-pattern>/WEB-INF/*</url-pattern>
</filter-mapping>

<filter-mapping>
<filter-name>LoginFilter</filter-name>
<url-pattern>*.jsp</url-pattern>
</filter-mapping>

到此为止,主要为自己做备忘,同时方便有需要的人。呵呵!

上一篇:Django(二)


下一篇:oracle-sql入门练习及答案