首页 > 代码库 > spring 过滤器- 过滤登陆请求路径(过滤静态资源跳转到登陆页面)

spring 过滤器- 过滤登陆请求路径(过滤静态资源跳转到登陆页面)

public class LoginedFilter implements Filter {

/**
* 排除的地址
*/
private Map<String, Boolean> ignore;
/**
* 排除的后缀
*/
private Map<String, Boolean> ignoreExt;

/**
* <b>功能描述:</b>实现接口,登录验证<br>
* <b>修订记录:</b><br>

*/
@Override
public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throws IOException,
ServletException {
HttpServletRequest request = (HttpServletRequest)arg0;
HttpServletResponse response = (HttpServletResponse) arg1;

String a = request.getRequestURI();

String ss = request.getRequestURI().replaceFirst(request.getContextPath(), "");

String address = request.getRequestURI().replaceFirst(request.getContextPath(), "").substring(1);

String ext = "";
if(address.lastIndexOf(".") > 0) {
ext = address.substring(address.lastIndexOf(".") + 1);
}
if(address.indexOf("/") != -1) {
address = address.substring(address.indexOf("/") + 1, address.length());
}


if(null == this.ignore.get(address) && null == this.ignoreExt.get(ext)) {
HttpSession session = request.getSession();
// 如果session为空,则跳转到登录页面。
// if(null == session.getAttribute("user") || session.isNew()) {
response.sendRedirect(request.getContextPath()+"/index");
return ;
//}
}
arg2.doFilter(arg0, arg1);

}

@Override
public void init(FilterConfig config) throws ServletException {
// 初始化排除列表
if(null == this.ignore) {
this.ignore = new HashMap<String, Boolean>();
}
if(null == this.ignoreExt) {
this.ignoreExt = new HashMap<String, Boolean>();
}
// 读取web.xml中的配置列表,装入Map对象,排除内容为Key,Value为true。
String ignoreConfig = config.getInitParameter("ignore");
String[] ignoreConfigArray = ignoreConfig.split(",");
for(String string : ignoreConfigArray) {
this.ignore.put(string.trim(), true);
}
String ignoreExtConfig = config.getInitParameter("ignoreExt");
String[] ignoreExtConfigArray = ignoreExtConfig.split(",");
for(String string : ignoreExtConfigArray) {
this.ignoreExt.put(string.trim(), true);
}
}

@Override
public void destroy() {
// 销毁时清除排除列表
this.ignore.clear();
this.ignore = null;
this.ignoreExt.clear();
this.ignoreExt = null;
}

//下面是web.xml 配置

<filter>
<filter-name>urlfilter</filter-name>
<filter-class>com.payease.chains.order.common.Filter.LoginedFilter</filter-class>
<init-param>
<description>排除过滤的前缀</description>
<param-name>ignore</param-name>
<param-value>index,chains,main,fund,order,fundDetail,orderList,logout,OmsUpload,merchant,upload,main1,main2</param-value>
</init-param>
<init-param>
<description>排除过滤的后缀</description>
<param-name>ignoreExt</param-name>
<param-value>js,css,jpg,gif,png,bmp,jpeg,ico</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>urlfilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>urlfilter</filter-name>
<url-pattern>/**</url-pattern>
</filter-mapping>










spring 过滤器- 过滤登陆请求路径(过滤静态资源跳转到登陆页面)