SpringBoot中使用Filter的两种方法
在SpringBoot中使用Filter也有两种方式:注解注册Filter和代码注册Filter,下面分别进行举例。
通过注解的方式进行注册
首先,创建一个Filter,并使用WebFilter
注解进行修饰,表示该类是一个Filter,以便于启动类进行扫描的时候确认,代码如下:
package org.framework.demo.section1;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
/**
* 在SpringBoot中通过注解注册的方式简单的使用Filter
* @author chengxi
*/
@WebFilter(urlPatterns = "/*", filterName = "myfilter")
public class FileterController implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("Filter初始化中");
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println("开始进行过滤处理");
//调用该方法后,表示过滤器经过原来的url请求处理方法
filterChain.doFilter(servletRequest, servletResponse);
}
@Override
public void destroy() {
System.out.println("Filter销毁中");
}
}
然后创建一个启动类,该启动类中同样额外添加一个注解用于自动扫描指定包下(默认是与启动类同包下)的WebFilter
/WebServlet
/WebListener
等特殊类,代码如下:
package org.springframework.demo.section;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
/**
* 启动类测试
* @author chengxi
*/
@SpringBootApplication
//该注解会扫描相应的包
@ServletComponentScan
public class Main {
public static void main(String[] args){
SpringApplication.run(Main.class, args);
}
}
通过代码注册的方式来注册Filter
首先,创建一个Filter类,该类不使用WebFilter
进行修饰:
package org.framework.demo.section1;
import javax.servlet.*;
import java.io.IOException;
/**
* 在SpringBoot中简单使用Filter
* @author chengxi
*/
public class FileterController implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("Filter初始化中");
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println("开始进行过滤处理");
//调用该方法后,表示过滤器经过原来的url请求处理方法
filterChain.doFilter(servletRequest, servletResponse);
}
@Override
public void destroy() {
System.out.println("Filter销毁中");
}
}
然后,编写启动类,这里的启动类就不能直接使用注解ServletComponentScan
来自动扫描了,需要我们手动添加代码来进行注册,需要用到的注册类是:FilterRegistrationBean
,代码方式注册Filter代码如下:
package org.springframework.demo.section;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
/**
* 启动类测试
* @author chengxi
*/
@SpringBootApplication
public class Main {
/**
* 代码方式注册Bean
* @return
*/
@Bean
public FilterRegistrationBean setFilter(){
FilterRegistrationBean filterBean = new FilterRegistrationBean();
filterBean.setFilter(new FilterController());
filterBean.setName("FilterController");
filterBean.addUrlPatterns("/*");
return filterBean;
}
public static void main(String[] args){ SpringApplication.run(Main.class, args); } }
====================过滤请求URL和ip===================
1 //不写属性全过滤 2 @WebFilter 3 @Slf4j 4 public class OpenapiFilter implements Filter { 5 6 private static final String UNKNOWN = "unknown"; 7 8 @Resource(name = "vehiclePropertyCache") 9 private PropertyCache propertyCache; 10 11 @Override 12 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) 13 throws IOException, ServletException { 14 HttpServletRequest httpServletRequest = (HttpServletRequest) request; 15 16 String requestURI = httpServletRequest.getRequestURI(); 17 //----/insurance-openapi/openapi/111/underwrite 18 log.info("requestURI"+requestURI); 19 20 //String substring = requestURI.substring("".length(), requestURI.length()); 21 String[] substring = requestURI.split("/openapi/"); 22 if (substring.length<2) { 23 returnJson(response,OpenapiEnum.ILLEGAL_REQUEST.getCode(),OpenapiEnum.ILLEGAL_REQUEST.getMessage()); 24 return ; 25 } 26 27 log.info("substring"+substring[1]); 28 29 String[] split = substring[1].split("/"); 30 String partnerCode = split[0]; 31 // 校验请求是否合法. 32 33 if (StringUtils.isBlank(partnerCode)) { 34 returnJson(response,OpenapiEnum.ILLEGAL_REQUEST.getCode(),OpenapiEnum.ILLEGAL_REQUEST.getMessage()); 35 return ; 36 } 37 38 39 //获取ip地址 校验请求的服务ip是否在配置内 40 String ipAddress = this.getIpAddress(httpServletRequest); 41 //获取白名单 42 Object object = propertyCache.getProperty("/openapi/ins/"+partnerCode, "white_list"); 43 //白名单不为空进行判断 44 if (object!=null) { 45 JSONObject whiteList = (JSONObject)object; 46 //获取是否启用白名单标志 47 String enable = whiteList.getString("enable"); 48 //如果为true 就启用 49 if ("true".equals(enable)) { 50 //获取白名单ip 51 JSONArray jsonArray = whiteList.getJSONArray("whiteListIp"); 52 //等于空就返回非法请求 53 if (null==jsonArray) { 54 returnJson(response,OpenapiEnum.ILLEGAL_REQUEST.getCode(),OpenapiEnum.ILLEGAL_REQUEST.getMessage()); 55 return ; 56 } 57 //不包含就返回非法请求 58 if (!jsonArray.contains(ipAddress)) { 59 returnJson(response,OpenapiEnum.ILLEGAL_REQUEST.getCode(),OpenapiEnum.ILLEGAL_REQUEST.getMessage()); 60 return; 61 } 62 } 63 } 64 65 66 67 68 JSONArray property = (JSONArray)propertyCache.getProperty("/openapi/ins/"+partnerCode, "requestUrl"); 69 if (null==property) { 70 returnJson(response,OpenapiEnum.ILLEGAL_REQUEST.getCode(),OpenapiEnum.ILLEGAL_REQUEST.getMessage()); 71 return ; 72 } 73 74 if (!property.contains(substring[1])&&!property.contains("/"+substring[1])) { 75 returnJson(response,OpenapiEnum.PERMISSION_DENIED.getCode(),OpenapiEnum.PERMISSION_DENIED.getMessage()); 76 return; 77 } 78 79 chain.doFilter(request, response); 80 81 } 82 83 private void returnJson(ServletResponse response, String code, String message){ 84 PrintWriter writer = null; 85 response.setCharacterEncoding("UTF-8"); 86 response.setContentType("text/html; charset=utf-8"); 87 try { 88 writer = response.getWriter(); 89 JSONObject json = new JSONObject(); 90 json.put("responseCode", code); 91 json.put("responseMsg", message); 92 writer.print(json); 93 94 } catch (IOException e) { 95 log.error("response error",e); 96 } finally { 97 if (writer != null) 98 writer.close(); 99 } 100 } 101 102 103 /** 104 * 获取请求主机IP地址,如果通过代理进来,则透过防火墙获取真实IP地址; 105 * 106 * @param request 107 * @return 108 * @throws IOException 109 */ 110 private String getIpAddress(HttpServletRequest request) throws IOException { 111 // 获取请求主机IP地址,如果通过代理进来,则透过防火墙获取真实IP地址 112 log.info("getIpAddress(HttpServletRequest)===========start"); 113 String ip = request.getHeader("X-Forwarded-For"); 114 System.out.println("==X-Forwarded-For===ipAddress====" + ip); 115 log.info("getIpAddress(HttpServletRequest) - X-Forwarded-For - String ip=" + ip); 116 117 if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) { 118 if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) { 119 ip = request.getHeader("Proxy-Client-IP"); 120 log.info("getIpAddress(HttpServletRequest) - Proxy-Client-IP - String ip=" + ip); 121 } 122 if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) { 123 ip = request.getHeader("WL-Proxy-Client-IP"); 124 log.info("getIpAddress(HttpServletRequest) - WL-Proxy-Client-IP - String ip=" + ip); 125 } 126 if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) { 127 ip = request.getHeader("HTTP_CLIENT_IP"); 128 log.info("getIpAddress(HttpServletRequest) - HTTP_CLIENT_IP - String ip=" + ip); 129 } 130 if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) { 131 ip = request.getHeader("HTTP_X_FORWARDED_FOR"); 132 log.info("getIpAddress(HttpServletRequest) - HTTP_X_FORWARDED_FOR - String ip=" + ip); 133 } 134 if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) { 135 ip = request.getRemoteAddr(); 136 log.info("getIpAddress(HttpServletRequest) - getRemoteAddr - String ip=" + ip); 137 138 } 139 } else if (ip.length() > 15) { 140 String[] ips = ip.split(","); 141 for (int index = 0; index < ips.length; index++) { 142 String strIp = (String) ips[index]; 143 if (!(UNKNOWN.equalsIgnoreCase(strIp))) { 144 ip = strIp; 145 break; 146 } 147 } 148 } 149 log.info("getIpAddress(HttpServletRequest) getIpAddress==end==ip=" + ip); 150 return ip; 151 } 152 }