首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 移动开发 > 移动开发 >

加入监听跟过滤器来实现url地址的控制.在项目中很实用

2012-07-08 
加入监听和过滤器来实现url地址的控制.在项目中很实用.博客分类: java ServletXMLApachelog4jWeb好处: 不

加入监听和过滤器来实现url地址的控制.在项目中很实用.
博客分类: java
ServletXMLApachelog4jWeb
好处: 不用再在N多个页面包含



Java代码 
if(session.getAttribute("user")==null)  
    response.sendRedirect("index.htm"); 

if(session.getAttribute("user")==null)
    response.sendRedirect("index.htm");

这样的垃圾代码了.



首先说下主要代码实现方式:



web.xml中的监听和过滤器:

Java代码 
<context-param>  
                 <!-- 允许不登陆就可以访问的页面参数 -->  
        <param-name>allowPath</param-name>   
                <!-- xml配置实现参数配置 -- >                 
    <param-value>allowPath.xml</param-value>  
    </context-param>  
      
    <filter>  
                            <!-- 监听url请求,验证是否可以访问 -- >  
        <filter-name>UserAdmin</filter-name>  
        <filter-class>com.thams.framework.filter.AuthFilter</filter-class>  
        <init-param>  
            <param-name>allowRole</param-name>  
            <param-value>1</param-value>  
        </init-param>  
    </filter>  
    <!-- 初始化xml的配置.把允许访问的url在xml中的配置读取进来 -- >  
    <filter-mapping>  
        <filter-name>UserAdmin</filter-name>  
                                    <!-- 默认是该工程下所有请求都监听 -- >  
        <url-pattern>/*</url-pattern>  
    </filter-mapping>  
      
    <listener>  
        <listener-class>com.thams.framework.listener.ContextListener</listener-class>  
    </listener> 

<context-param>
                 <!-- 允许不登陆就可以访问的页面参数 -->
    <param-name>allowPath</param-name>
                <!-- xml配置实现参数配置 -- >              
   <param-value>allowPath.xml</param-value>
  </context-param>

<filter>
                            <!-- 监听url请求,验证是否可以访问 -- >
<filter-name>UserAdmin</filter-name>
<filter-class>com.thams.framework.filter.AuthFilter</filter-class>
<init-param>
<param-name>allowRole</param-name>
<param-value>1</param-value>
</init-param>
</filter>
<!-- 初始化xml的配置.把允许访问的url在xml中的配置读取进来 -- >
<filter-mapping>
<filter-name>UserAdmin</filter-name>
                                    <!-- 默认是该工程下所有请求都监听 -- >
<url-pattern>/*</url-pattern>
</filter-mapping>

<listener>
    <listener-class>com.thams.framework.listener.ContextListener</listener-class>
</listener> allowPath.xml 允许访问的url地址 放在src下.如果改变 比如在WEB-INF下.需要修改文件读取路径

Java代码 
<?xml version="1.0" encoding="GB2312"?>  
<Config>  
    <!-- unprotectedurl 系统不受访问限制的URL配置文件 -->  
   <unprotectedurls>  
   <unprotectedurl url="collectAction.do"/>  
    <unprotectedurl url="loginAction.do"/>  
    <unprotectedurl url="login.jsp"/>  
    <unprotectedurl url="login.html"/>  
    <unprotectedurl url="js"/>  
    <unprotectedurl url="css"/>  
    <unprotectedurl url="jpg"/>  
    <unprotectedurl url="gif"/>  
    <unprotectedurl url="png"/>  
   </unprotectedurls>  
</Config> 

<?xml version="1.0" encoding="GB2312"?>
<Config>
    <!-- unprotectedurl 系统不受访问限制的URL配置文件 -->
   <unprotectedurls>
   <unprotectedurl url="collectAction.do"/>
    <unprotectedurl url="loginAction.do"/>
    <unprotectedurl url="login.jsp"/>
    <unprotectedurl url="login.html"/>
    <unprotectedurl url="js"/>
    <unprotectedurl url="css"/>
    <unprotectedurl url="jpg"/>
    <unprotectedurl url="gif"/>
    <unprotectedurl url="png"/>
   </unprotectedurls>
</Config>




AuthFilter.java 过滤器



Java代码 
/* 
* @(#)RoleDAO.java        2005/10/18 

* Copyright (c) 2003-2005 ASPire Technologies, Inc. 
* 6/F,IER BUILDING, SOUTH AREA,SHENZHEN HI-TECH INDUSTRIAL PARK Mail Box:11# 12#. 
* All rights reserved. 
*/ 
package com.thams.framework.filter;  
 
import java.io.File;  
import java.io.IOException;  
import java.util.ArrayList;  
import java.util.Iterator;  
import java.util.List;  
 
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.HttpServlet;  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  
 
import org.apache.commons.lang.StringUtils;  
import org.apache.commons.logging.Log;  
import org.apache.commons.logging.LogFactory;  
import org.apache.log4j.Logger;  
import org.jdom.Element;  
import org.jdom.input.SAXBuilder;  
 
import com.thams.user.UserSession;  
 
/** 
* <p> 
* Title: securityservice 
* </p> 
*  
* @author liuyuhua 
* @version 1.0 
*/ 
public class AuthFilter extends HttpServlet implements Filter {  
    private static final long serialVersionUID = -2641564339123115818L;  
    private FilterConfig filterConfig;  
    private static Logger log = Logger.getLogger(AuthFilter.class);  
    public static ArrayList unProtectedRes = null;  
    private static Element rootElement = null;  
    /** 
     * 重定向的URL 
     */ 
    private String redirectURl = null;  
 
    public AuthFilter() {  
    }  
 
    public void init(FilterConfig filtercfg)  
            throws javax.servlet.ServletException {  
        getUnprotectedResources();  
        redirectURl = "login.html";  
    }  
 
    /** 
     * 在过滤器中实现权限控制 
     */ 
    public void doFilter(ServletRequest sRequest, ServletResponse sResponse,  
            FilterChain filterChain) throws IOException, ServletException {  
        HttpServletRequest request = (HttpServletRequest) sRequest;  
        HttpServletResponse response = (HttpServletResponse) sResponse;  
        // 获取网站根目录  
        String path = request.getContextPath();  
        String basePath = request.getScheme() + "://" + request.getServerName()  
                + ":" + request.getServerPort() + path + "/";  
        try {  
            if (UserSession.isLogin(request)) { //如果登陆或者没有登陆但是有该url访问权限  
                filterChain.doFilter(request, response);  
                return;  
            }   
            if(isUnprotectedUrl(request)){  
                filterChain.doFilter(request, response);  
                return;  
            }else {  
                response.sendRedirect(basePath + redirectURl);  
                return;  
            }  
        } catch (Exception e) {  
            log.error("AuthFilter error:", e);  
        }  
    }  
 
    /** 
     * 是否有该页面访问权限 
     * @param request 
     * @return 
     */ 
    private boolean isUnprotectedUrl(HttpServletRequest request) {  
        String url = request.getRequestURI().toString();  
        int index = url.lastIndexOf("/");  
        if (index > -1) {  
            url = url.substring(index + 1);  
        }  
        for (int i = 0; i < unProtectedRes.size(); i++) {  
            String temp = (String) unProtectedRes.get(i);  
            if (url.endsWith(temp))  
                return true;  
        }  
//      if (url.endsWith(".do")) {  
//          url = url + "?" + request.getQueryString();  
//          for (int i = 0; i < unProtectedRes.size(); i++) {  
//              String temp = (String) unProtectedRes.get(i);  
//              if (url.indexOf(temp) > -1)  
//                  return true;  
//          }  
//      }  
        return false;  
    }  
 
    public void destroy() {  
    }  
 
    /** 
     * 载入配置文件 
     *  
     * @param cfg 
     *            配置文件名称 
     */ 
    public static void load(String cfg) {  
        try {  
            rootElement = new SAXBuilder().build(new File(cfg))  
                    .getRootElement();  
        } catch (Exception e) {  
            log.error(e.getMessage());  
        }  
    }  
 
    /** 
     * 获得配置文件中指定名称的Element 
     *  
     * @param elementName 
     * @return 
     */ 
    public static Element getElement(String elementName) {  
        return rootElement.getChild(elementName);  
    }  
 
    /** 
     * 获取不受访问限制的资源信息列表,调用之前需要先执行load()方法; 
     */ 
    public static void getUnprotectedResources() {  
 
        if (unProtectedRes == null) {  
            unProtectedRes = new ArrayList();  
            List urlList = new ArrayList();  
            Element interceptors = getElement("unprotectedurls");  
            urlList = interceptors.getChildren("unprotectedurl");  
            Iterator it = urlList.iterator();  
            Element tmpElement = null;  
            while (it.hasNext()) {  
                tmpElement = (Element) it.next();  
                unProtectedRes.add(tmpElement.getAttributeValue("url"));  
            }  
        }  
    }  
 
    public static void main(String[] args) {  
 
        AuthFilter tools = new AuthFilter();  
        tools.load("allowPath.xml");  
        tools.getUnprotectedResources();  
//      System.out.println(unProtectedRes.toString());  
 
    }  
 


/*
* @(#)RoleDAO.java        2005/10/18
*
* Copyright (c) 2003-2005 ASPire Technologies, Inc.
* 6/F,IER BUILDING, SOUTH AREA,SHENZHEN HI-TECH INDUSTRIAL PARK Mail Box:11# 12#.
* All rights reserved.
*/
package com.thams.framework.filter;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

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.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.Logger;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;

import com.thams.user.UserSession;

/**
* <p>
* Title: securityservice
* </p>
*
* @author liuyuhua
* @version 1.0
*/
public class AuthFilter extends HttpServlet implements Filter {
private static final long serialVersionUID = -2641564339123115818L;
private FilterConfig filterConfig;
private static Logger log = Logger.getLogger(AuthFilter.class);
public static ArrayList unProtectedRes = null;
private static Element rootElement = null;
/**
* 重定向的URL
*/
private String redirectURl = null;

public AuthFilter() {
}

public void init(FilterConfig filtercfg)
throws javax.servlet.ServletException {
getUnprotectedResources();
redirectURl = "login.html";
}

/**
* 在过滤器中实现权限控制
*/
public void doFilter(ServletRequest sRequest, ServletResponse sResponse,
FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) sRequest;
HttpServletResponse response = (HttpServletResponse) sResponse;
// 获取网站根目录
String path = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName()
+ ":" + request.getServerPort() + path + "/";
try {
if (UserSession.isLogin(request)) { //如果登陆或者没有登陆但是有该url访问权限
filterChain.doFilter(request, response);
return;
}
if(isUnprotectedUrl(request)){
filterChain.doFilter(request, response);
return;
}else {
response.sendRedirect(basePath + redirectURl);
return;
}
} catch (Exception e) {
log.error("AuthFilter error:", e);
}
}

/**
* 是否有该页面访问权限
* @param request
* @return
*/
private boolean isUnprotectedUrl(HttpServletRequest request) {
String url = request.getRequestURI().toString();
int index = url.lastIndexOf("/");
if (index > -1) {
url = url.substring(index + 1);
}
for (int i = 0; i < unProtectedRes.size(); i++) {
String temp = (String) unProtectedRes.get(i);
if (url.endsWith(temp))
return true;
}
//if (url.endsWith(".do")) {
//url = url + "?" + request.getQueryString();
//for (int i = 0; i < unProtectedRes.size(); i++) {
//String temp = (String) unProtectedRes.get(i);
//if (url.indexOf(temp) > -1)
//return true;
//}
//}
return false;
}

public void destroy() {
}

/**
* 载入配置文件
*
* @param cfg
*            配置文件名称
*/
public static void load(String cfg) {
try {
rootElement = new SAXBuilder().build(new File(cfg))
.getRootElement();
} catch (Exception e) {
log.error(e.getMessage());
}
}

/**
* 获得配置文件中指定名称的Element
*
* @param elementName
* @return
*/
public static Element getElement(String elementName) {
return rootElement.getChild(elementName);
}

/**
* 获取不受访问限制的资源信息列表,调用之前需要先执行load()方法;
*/
public static void getUnprotectedResources() {

if (unProtectedRes == null) {
unProtectedRes = new ArrayList();
List urlList = new ArrayList();
Element interceptors = getElement("unprotectedurls");
urlList = interceptors.getChildren("unprotectedurl");
Iterator it = urlList.iterator();
Element tmpElement = null;
while (it.hasNext()) {
tmpElement = (Element) it.next();
unProtectedRes.add(tmpElement.getAttributeValue("url"));
}
}
}

public static void main(String[] args) {

AuthFilter tools = new AuthFilter();
tools.load("allowPath.xml");
tools.getUnprotectedResources();
//System.out.println(unProtectedRes.toString());

}

}


ContextListener.java 监听. 其实这个可以放在servlet的init方法中,只要实现启动时候加载下就可以了



Java代码 
package com.thams.framework.listener;  
 
import java.io.File;  
import java.io.IOException;  
import java.net.MalformedURLException;  
import java.util.Enumeration;  
 
import javax.servlet.ServletContext;  
import javax.servlet.ServletContextEvent;  
import javax.servlet.ServletContextListener;  
import javax.servlet.http.HttpServlet;  
 
import org.apache.log4j.Logger;  
 
import com.thams.codetable.CodeTableCollection;  
import com.thams.codetable.CodeTableService;  
import com.thams.framework.ServiceFactory;  
import com.thams.framework.filter.AuthFilter;  
 
public class ContextListener extends HttpServlet implements 
        ServletContextListener {  
    private static Logger log = Logger.getLogger(ContextListener.class);  
    /** 
     * web应用启动的时候会执行,方法里面可以初始化配置文件,启动线程等初始化操作 
     *  
     * @param sce 
     *            ServletContextEvent 
     */ 
    public void contextInitialized(ServletContextEvent sce) {  
        ServletContext servletContext = sce.getServletContext();  
        Enumeration enumeration = servletContext.getInitParameterNames();  
        //在application context里面放入字段信息的数据结构  
        String key = null;  
        String value = null;  
        while (enumeration.hasMoreElements()) {  
            key = (String) enumeration.nextElement();  
            value = servletContext.getInitParameter(key);  
            if (key.equals("allowPath")) {  
                // to load unprotected parameters  
                try {  
                    String configPath = this.getClass().getClassLoader().getResource("allowPath.xml").getFile();//("allowPath.xml").getPath();  
                    configPath = java.net.URLDecoder.decode(configPath,"utf-8");  
                    AuthFilter.load(configPath);  
                    log.debug("unprotected resource infomation has loaded.");  
                } catch (Exception ex) {  
                    log.error("Failed to load unprotected resource infomation "+ex.getMessage());  
                }  
            }  
 
        }  
    }  
 
    public void contextDestroyed(ServletContextEvent sce) {  
    }  
 


package com.thams.framework.listener;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.Enumeration;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.http.HttpServlet;

import org.apache.log4j.Logger;

import com.thams.codetable.CodeTableCollection;
import com.thams.codetable.CodeTableService;
import com.thams.framework.ServiceFactory;
import com.thams.framework.filter.AuthFilter;

public class ContextListener extends HttpServlet implements
ServletContextListener {
private static Logger log = Logger.getLogger(ContextListener.class);
/**
* web应用启动的时候会执行,方法里面可以初始化配置文件,启动线程等初始化操作
*
* @param sce
*            ServletContextEvent
*/
public void contextInitialized(ServletContextEvent sce) {
ServletContext servletContext = sce.getServletContext();
Enumeration enumeration = servletContext.getInitParameterNames();
//在application context里面放入字段信息的数据结构
String key = null;
String value = null;
while (enumeration.hasMoreElements()) {
key = (String) enumeration.nextElement();
value = servletContext.getInitParameter(key);
if (key.equals("allowPath")) {
// to load unprotected parameters
try {
String configPath = this.getClass().getClassLoader().getResource("allowPath.xml").getFile();//("allowPath.xml").getPath();
configPath = java.net.URLDecoder.decode(configPath,"utf-8");
AuthFilter.load(configPath);
log.debug("unprotected resource infomation has loaded.");
} catch (Exception ex) {
log.error("Failed to load unprotected resource infomation "+ex.getMessage());
}
}

}
}

public void contextDestroyed(ServletContextEvent sce) {
}

}


这样配置后.



比如你的工程叫AMS



则所有访问http://你的服务器IP:端口/AMS/* 路径的url都将被AuthFilter.java这个过滤器过滤.里面可以是你自己的逻辑.也可以是只是判断用户是否已经登陆.





UserSession.java 放上来大家参考下.估计对大家有用.



Java代码 
package com.thams.user;  
 
import javax.servlet.http.HttpServletRequest;  
 
import com.thams.dao.po.SUser;  
import com.thams.userRoleRight.UserRoleRight;  
 
/** 
* @Function: 方便用户得到和set UserSession 
* @author: luyu 
* @date: Nov 12, 2008 
*/ 
public class UserSession {  
      
    public static final String USER_SESSION = "userSession";  
      
    /** 
     * 判断用户是否登陆 
     * @param request 
     * @return 如果是返回true,否则返回false 
     */ 
    public static boolean isLogin(HttpServletRequest request) {  
        UserSession userSession = (UserSession)request.getSession(true).getAttribute(USER_SESSION);  
        if (userSession!=null) {  
            return true;  
        }  
        return false;  
    }  
      
    public static boolean logout(HttpServletRequest request) {  
        UserSession userSession = (UserSession)request.getSession(true).getAttribute(USER_SESSION);  
        if (null != userSession) {  
            return true;  
        }  
        return true;  
    }  
      
    /** 
     * 从session中得到用户名 
     * @param request 
     * @return 返回用户名 
     */ 
    public static SUser getUser(HttpServletRequest request){  
        UserSession userSession = (UserSession) request.getSession(true).getAttribute(USER_SESSION);  
        if(null == userSession){  
            return null;  
        }  
        return userSession.getUser();  
    }  
      
    /** 
     * 保存userSession到HttpSession里 
     * @param request 
     * @param userSession  
     */ 
    public static void saveUserSession(HttpServletRequest request,UserSession userSession){  
        request.getSession(true).setAttribute(USER_SESSION, userSession);  
    }  
      
    /** 
     * @function: 得到UserSession 
     * @author: luyu 
     * @data: Sep 3, 2008 
     * @param request 
     * @return 得到UserSession 
     */ 
    public static UserSession getUserSession(HttpServletRequest request){  
        UserSession userSession = (UserSession)request.getSession(true).getAttribute(USER_SESSION);  
        if (userSession == null) {  
            return null;  
        }  
        return userSession;  
    }  
      
 
    public SUser getUser() {  
        return user;  
    }  
 
 
    public void setUser(SUser user) {  
        this.user = user;  
    }  
 
 
    public UserRoleRight getUserRoleRight() {  
        return userRoleRight;  
    }  
 
 
    public void setUserRoleRight(UserRoleRight userRoleRight) {  
        this.userRoleRight = userRoleRight;  
    }  
      
    private SUser user = null;  
      
    private UserRoleRight userRoleRight= null;  

热点排行