java拦截器Filter中注入Spring Bean

接上篇ajax跨域携带Cookie信息,项目中服务端拿到Cookie信息后,需要查询数据库用户信息,做登录验证。

按照平时习惯直接使用注解@Autowired会报service空指针异常,具体原因网上有很多介绍,这里不多赘述。

解决这个问题,网上的答案基本都是使用spring filter代理或在Filter中使用ApplicationContext对象获取bean。

但是我们项目是使用dubbo搭建,使用这些方式都无法获取bean对象,最后使用了注解@Component解决。

spring xml配置文件中必须配置扫描拦截器所在包路径。

1、web.xml配置拦截器:

    
        headFilter
        com.jdy.filter.HeaderFilter
    
    
        headFilter
        /*  
    

2、spring.xml配置扫描路径:




3、拦截器Class类代码如下:

package com.jdy.filter;

import ........;

@Component
public class HeaderFilter implements Filter {

    private static final Logger logger = LoggerFactory.getLogger(HeaderFilter.class);

    @Autowired
    private AdServiceApi adServiceApi;

    @Autowired
    private UserServiceApi userServiceApi;

    @Autowired
    private SysTokenServiceApi sysTokenServiceApi;

    private static HeaderFilter headerFilter;

    public void setAdServiceApi(AdServiceApi adServiceApi) {
        this.adServiceApi = adServiceApi;
    }

    public void setSysTokenServiceApi(SysTokenServiceApi sysTokenServiceApi) {
        this.sysTokenServiceApi = sysTokenServiceApi;
    }

    public void setUserServiceApi(UserServiceApi userServiceApi) {
        this.userServiceApi = userServiceApi;
    }

    @PostConstruct
    public void init() {
        headerFilter = this;
        headerFilter.adServiceApi = this.adServiceApi;
        headerFilter.sysTokenServiceApi = this.sysTokenServiceApi;
        headerFilter.userServiceApi = this.userServiceApi;
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        try {
            logger.info("----------------进入拦截器---------------");
            
            //获取登录信息
            String token = CookieUtils.getCookieValue(request, "token");
            //查询用户信息
            String sysToken = headerFilter.sysTokenServiceApi.getByReqSign(token);
            //TODO: 业务处理
            ............
        }catch (Exception ex){
            logger.info("系统异常!");
            ex.printStackTrace();
        }
        logger.info("------------拦截结束----------");
        filterChain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }
}

注:service调用时,必须以当前类名变量.service.接口名称,这种方式调用。

你可能感兴趣的:(java)