springboot过滤器
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;
public class BmXyCnsFilter extends OncePerRequestFilter {
MyRestTemplate restTemplate;
List list;
@Override
protected void initFilterBean() throws ServletException {
ServletContext servletContext = getServletContext();
WebApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(servletContext);
restTemplate= webApplicationContext.getBean(MyRestTemplate.class);
//从spring容器中获取到jxJson bean对象
//可查看上一个博客,路径:https://blog.csdn.net/Denial_learn/article/details/122415367?spm=1001.2014.3001.5501
list=(List) webApplicationContext.getBean("jxJson");
}
@Override
protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
HttpSession session = httpServletRequest.getSession();
Visit visit = (Visit) session.getAttribute("SESSION_VISIT_______");
String requestURI = httpServletRequest.getRequestURI();
String substring = requestURI.substring(requestURI.indexOf("/"), requestURI.length());
//业务逻辑
{业务逻辑}
filterChain.doFilter(httpServletRequest,httpServletResponse);
}
}
使过滤器生效
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class FilterConfig {
@Bean
public FilterRegistrationBean getBmXyFilter(){
FilterRegistrationBean registrationBean = new FilterRegistrationBean();
registrationBean.setFilter(new BmXyCnsFilter());
registrationBean.addUrlPatterns("/*");
registrationBean.setName("bmxyFilter");
registrationBean.setOrder(2);
return registrationBean;
}
}