过滤器 拦截非法的url请求

原创
2016/04/08 17:20
阅读数 978

package com.hrt.frame.filter;

import java.io.IOException;

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 javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.hrt.frame.entity.model.UserModel;

/**
* 权限检查过滤器
*
* @author  lichao
* @date  2014-4-1
* @version  1.0
*/
@SuppressWarnings("serial")
public class UrlFilter extends HttpServlet implements Filter {

private Log log = LogFactory.getLog(UrlFilter.class);

private final String LOGIN_PATH = "/HrtApp/";//登陆页
private final String LOGIN_REDIRECT = "user_login.action";//登陆跳转
private final String LOGIN_RAND = "rand.action";//验证码

public void doFilter(ServletRequest request, ServletResponse response,
FilterChain filterChain) throws IOException, ServletException {
HttpServletResponse hresponse = (HttpServletResponse) response;
HttpServletRequest hrequest = (HttpServletRequest) request;
HttpSession session = hrequest.getSession(true);
Object user = session.getAttribute("user");//
String url = hrequest.getRequestURI();
if (user == null) {
// 判断获取的路径不为空且不是访问登录页面或执行登录操作时跳转
if (url != null && !url.equals("") && (!url.endsWith(LOGIN_PATH))&& (!url.endsWith(LOGIN_REDIRECT))&& (!url.endsWith(LOGIN_RAND))) {
log.info("非法路径请求url-----》"+url);
hresponse.sendRedirect("/HrtApp");
return;
}
}
// 已通过验证,用户访问继续
filterChain.doFilter(request, response);
return;
}

public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub

}

}





web。xml添加配置内容
<!-- urlFilter -->
<filter>
<filter-name>urlFilter</filter-name>
<filter-class>com.hrt.frame.filter.UrlFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>urlFilter</filter-name>
<url-pattern>*.jsp</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>urlFilter</filter-name>
<url-pattern>*.action</url-pattern>
</filter-mapping>

展开阅读全文
打赏
1
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
1
分享
返回顶部
顶部