spring mvc怎样在filter中获得bean?

如题,用@autoWired获取不到

 

以下是例子:

public class IPFilter implements Filter {

 /**
  * Logger for this class
  */
 public static final Logger logger = Logger.getLogger(IPFilter.class);

 private String excludedPages; //存储web.xml里面配置的filter的init-param的init-value
 private String[] pages; //excludedPages调用split方法后的String[]

 private UserIpFilterService userIpFilterService;

 @Override
 public void init(FilterConfig filterConfig) throws ServletException {
  excludedPages = filterConfig.getInitParameter("excludedPages"); //获取init-value
  pages = excludedPages.split(","); //使用,号分割excluded pages

  ServletContext context = filterConfig.getServletContext();
  ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(context);
  userIpFilterService = (UserIpFilterService) ac.getBean("userIpFilterService");

 }

 @Override
 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
   ServletException {

  HttpServletRequest req = (HttpServletRequest) request;
  HttpServletResponse res = (HttpServletResponse) response;
  String path = req.getContextPath();//取得根目录
  String userIp = request.getRemoteAddr();
  Boolean flag = userIpFilterService.selectUserByUserIP(userIp);

  boolean isExcludedPage = false;

  for (int i = 0; i < pages.length; i++) {

   //判断请求的页面是否excluded page
   if (req.getServletPath().equals(pages[i])) {
    isExcludedPage = true;
    break;
   }
  }

  if (isExcludedPage) {
   logger.info("This page does not need to filter.");
   chain.doFilter(request, response);

  } else if (flag == true) {
   logger.info("success.");
   chain.doFilter(request, response);

  } else {
   logger.info("redirect to :" + path + "/index.jsp");
   logger.info("fail.");
   res.sendRedirect(path + "/pages/fail.html");

  }

 }

 @Override
 public void destroy() {
  // TODO Auto-generated method stub

 }

}

你可能感兴趣的:(过滤器)