Java过滤ip,只允许配置的ip能够被访问
第一先创建过滤类 实现Filter就会有init(),doFilter(),destroy()三个方法
private String ips; public String getIps() { return ips; } public void setIps(String ips) { this.ips = ips; } public ipConfigFilter(String ips) { this.ips = ips; } public ipConfigFilter() { this.ips = ""; } @Override public void init(FilterConfig filterConfig) throws ServletException { ips = filterConfig.getInitParameter("ips"); String[] ipList = this.getIps().split(","); for (String ip : ipList) { logger.debug(ip); } } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { String[] ipList = this.getIps().split(","); String invokerIp = request.getRemoteAddr(); logger.debug("remot:" + invokerIp); boolean falg = Arrays.asList(ipList).contains(invokerIp); if (!falg) { response.setContentType("application/json;charset=UTF-8"); response.getWriter().print("{'code':'401','msg':'您无权限访问该地址'}"); } else { chain.doFilter(request, response); } } @Override public void destroy() { }
在web.xml里配置过滤信息
param-value可以配多个用逗号隔开
<filter> <filter-name>ipConfigFilter</filter-name> <filter-class>com.Filter.ipConfigFilter</filter-class> <async-supported>true</async-supported> <init-param> <param-name>ips</param-name> <param-value>10.1000.100.100,20.100.100.100</param-value> </init-param> </filter> <filter-mapping> <filter-name>ipConfigFilter</filter-name> <url-pattern>/page/pc-back/*</url-pattern> </filter-mapping> <session-config> <session-timeout>30</session-timeout> </session-config>