java web项目 IP控制 filter配置实例

最近工作需要做一个IP控制功能,项目有两个登陆页面,分为前台后台登陆页面。后台登陆页面,不要暴露给普通用户,需要进行IP控制。


1.web.xml 配置filter

<?xml version="1.0" encoding="utf-8"?>

<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	version="2.5">
	
	<welcome-file-list>
		<welcome-file>index.html</welcome-file>
		<welcome-file>index.htm</welcome-file>
	</welcome-file-list><filter>
		<filter-name>ipFilter</filter-name>
		<filter-class>com.esoft.archer.system.filter.IpFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>ipFilter</filter-name>
		<url-pattern>/admin/*</url-pattern>
	</filter-mapping>
</web-app>
这里需要注意的是你的filter的优先级别,如果你有多个filter的话请根据自己的优先级别,把需要优先过滤的条件放在最上面,filter的先进后出原则。



public class IpFilter implements Filter {

	private final static Log log = LogFactory.getLog(IpFilter.class);

	HibernateTemplate ht;

	LoginUserInfo loginUserInfo;

	@Override
	public void destroy() {
		if (log.isInfoEnabled()) {
			log.info("ipFilter destroyed...");
		}
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain filterChain) throws IOException, ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		HttpServletResponse httpResponse = (HttpServletResponse) response;
		ht = (HibernateTemplate) SpringBeanUtil.getBeanByName("ht");
		// 获取访问IP
		String ipString = getIpAddr(httpRequest);
		//业务相关,可以根据自己的业务要求修改
		String hql = "from AcceptLoginIp ali where ali.value=? and ali.status =?";

		List<AcceptLoginIp> alis = ht.find(hql, new String[] { ipString,ALIConstants.USABLE });

		if (alis != null && alis.size() > 0) {
			// 如果有继续...
			filterChain.doFilter(request, response);
		} else {
			// 重定向至错误页面
			httpResponse.sendRedirect("/qtwang/error");
		}
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		if (log.isInfoEnabled()) {
			log.info("ipFilter init start ...");
		}
	}

	protected String getIpAddr(HttpServletRequest request) {
		if (request.getHeader("x-forwarded-for") == null) {
			return request.getRemoteAddr();
		}
		return request.getHeader("x-forwarded-for");
	}
}


这里就没有什么好注意的了,唯一需要注意的就是加载过程中资源是否能访问的到,如果访问部到,自己根据自己的项目区修改下吧。


祝工作愉快!!!lol

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值