springBoot之配置文件的读取以及过滤器和拦截器的使用 (2)

那么在springBoot中如何使用过滤器呢?
一般是使用Component和WebFilter 这两个注解,但是这里我们就直接方法调用。
在该方法中添加Bean注解,springBoot会在启动的时候进行调用。并指定需要过滤的请求。

代码示例:

@Bean public FilterRegistrationBean testFilterRegistration() { FilterRegistrationBean registration = new FilterRegistrationBean(); registration.setFilter(new MyFilter()); //过滤掉 /getUser 和/hello 的请求 registration.addUrlPatterns("/getUser","/hello"); //过滤掉所有请求 // registration.addUrlPatterns("/*"); registration.setName("MyFilter"); registration.setOrder(1); return registration; }

说明: registration.setOrder() 方法是设置优先级,数值越大,优先级越高。

拦截器

拦截器是什么?
简单的来说,就是一道阀门,拦截不需要的东西。
拦截器主要做什么?
对正在运行的流程进行干预。

拦截器的代码实现。
拦截器也主要有三个方法,其中preHandle是在请求之前就进行调用,如果该请求需要被拦截,则返回false,否则true; postHandle是在请求之后进行调用,无返回值;afterCompletion是在请求结束的时候进行调用,无返回值。

这里我们就简单的模拟下拦截非白名单的IP请求。
代码示例:

class MyInterceptor implements HandlerInterceptor { @Autowired private IpConfig ipconfig; public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception { String ip = getIpAddr(request); // 获取可以访问系统的白名单 String ipStr = ipconfig.getIpWhiteList(); String[] ipArr = ipStr.split("\\|"); List<String> ipList = Arrays.asList(ipArr); if (ipList.contains(ip)) { System.out.println("该IP: " + ip+"通过!"); return true; } else { System.out.println("该IP: " + ip+"不通过!"); response.setCharacterEncoding("UTF-8"); response.setContentType("application/json; charset=utf-8"); // 消息 Map<String, Object> messageMap = new HashMap<>(); messageMap.put("status", "1"); messageMap.put("message", "您好,ip为" + ip + ",暂时没有访问权限,请联系管理员开通访问权限。"); ObjectMapper objectMapper=new ObjectMapper(); String writeValueAsString = objectMapper.writeValueAsString(messageMap); response.getWriter().write(writeValueAsString); return false; } } public String getIpAddr(HttpServletRequest request) { String ip = request.getHeader("X-Forwarded-For"); if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("WL-Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("HTTP_CLIENT_IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("HTTP_X_FORWARDED_FOR"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); } return ip; } @Override public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception { System.out.println("postHandle被调用"); } @Override public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception { System.out.println("afterCompletion被调用"); } }

依旧再启动springBoot的时候启动拦截器,并指定拦截的请求。

代码示例:

import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import com.fasterxml.jackson.databind.ObjectMapper; import com.pancm.springboot_config.config.IpConfig; @Configuration public class MyWebAppConfigurer extends WebMvcConfigurerAdapter { @Bean public HandlerInterceptor getMyInterceptor(){ return new MyInterceptor(); } @Override public void addInterceptors(InterceptorRegistry registry) { // addPathPatterns 用于添加拦截规则, 这里假设拦截 /url 后面的全部链接 // excludePathPatterns 用户排除拦截 registry.addInterceptor(getMyInterceptor()).addPathPatterns("/**"); super.addInterceptors(registry); } } 结语

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wspdjx.html