创建springboot过滤器

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;
    }

}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值