java web專案 IP控制 filter配置例項
阿新 • • 發佈:2019-02-16
最近工作需要做一個IP控制功能,專案有兩個登陸頁面,分為前臺後臺登陸頁面。後臺登陸頁面,不要暴露給普通使用者,需要進行IP控制。
1.web.xml 配置filter
這裡需要注意的是你的filter的優先級別,如果你有多個filter的話請根據自己的優先級別,把需要優先過濾的條件放在最上面,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>
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