前言:
在一些业务需求中有的是只能当前主机登录熊系统,或者说是当前的网段内用户可以访问,这时候就需要用到了servlet中的过滤器了。
放行指定IP:
编写过滤器:
package com.mixky.app.bjcc.filter; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import java.io.IOException; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; /** * @author zhangzhixi * @version 1.0 * @date 2021-8-16 16:38 */ public class NoteFilter implements Filter { private FilterConfig config = null; //ip白名单 private String ipTable = null; @Override public void init(FilterConfig filterConfig) throws ServletException { System.out.println("note filter initial"); this.config = filterConfig; /*获取白名单*/ this.ipTable = config.getInitParameter("ipTable"); } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { System.out.println("do filter starting"); /*校验ip地址:不是白名单就直接结束*/ if (!verifyIP(request, response)) { return; } long befor = System.currentTimeMillis(); config.getServletContext().log("before call note Filter"); chain.doFilter(request, response); config.getServletContext().log("after call note Filter"); long after = System.currentTimeMillis(); String name = ""; if (request instanceof HttpServletRequest) { name = ((HttpServletRequest) request).getRequestURI(); } config.getServletContext().log("Note Filter : name:" + name + " time :" + (after - befor) + "ms"); } @Override public void destroy() { } /** * 验证IP * * @param request 请求 * @param response 响应 * @return 校验结果 */ private boolean verifyIP(ServletRequest request, ServletResponse response) { /*获取本机IP地址*/ String ip = request.getLocalAddr(); /*windows下本机测试*/ if ("0:0:0:0:0:0:0:1".equals(ip)) { ip = "127.0.0.1"; System.out.println("请求ip:" + ip); } System.out.println("本机IP是:" + ip); System.out.println("ipTable白名单:" + ipTable); /*是白名单用户*/ if (ipTable.equals(ip)) { return true; } else { System.out.println("校验不通过"); /*设置编码*/ try { request.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); PrintWriter out = null; try { out = response.getWriter(); out.print("<h1>对不起,你的ip不能访问服务器</h1>"); out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return false; } } }
web.xml配置文件:
<!--IP过滤--> <filter> <filter-name>ip</filter-name> <filter-class>com.mixky.app.bjcc.filter.NoteFilter</filter-class> <init-param> <param-name>ipTable</param-name> <!--设置的白名单IP--> <param-value>127.0.0.1</param-value> </init-param> </filter> <filter-mapping> <filter-name>ip</filter-name> <!--过滤所有请求--> <url-pattern>/*</url-pattern> </filter-mapping>