Spring学习笔记-在Filter中获取SpingIOC容器

来源:互联网 发布:施工动画什么软件 编辑:程序博客网 时间:2024/06/10 15:20

在spring项目中,有时需要在filter中操作数据库,由于整个项目有spring容器进行管理,所有不能直接利用new来创建对象,需要从spring容器中获取所需对象,但是直接利用注解进行注入是行不通的,因为在整个项目架构中,Filter与Spring容器是解耦合的,那么怎么办的,看下面的代码示例:

public class ValidateFilter implements Filter{    private UserService userService;    private static WebApplicationContext ac;    @Override    public void destroy() {}    @Override    public void init(FilterConfig config) throws ServletException {    }    @Override    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)            throws IOException, ServletException {         HttpServletRequest request = (HttpServletRequest)req;         HttpServletResponse response = (HttpServletResponse)resp;         if(ac == null){             //获取Spring容器上下文             ac = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());         }         //从         userService = (UserService)ac.getBean("UserServiceImpl");         String config  = userService.getValidateConfig();         //如果标记为 1,则不进行密码验证过滤。         if("1".equals(config)){             chain.doFilter(request, response);         }else if("2".equals(config)){                 HttpSession session = request.getSession();                 String validateFlag = (String)session.getAttribute("validateFlag");                 if(validateFlag != null && "true".equals(validateFlag)){                      chain.doFilter(request, response);                 }else{                     String password = request.getParameter("password");                     if(password != null && "Garden9".equals(password)){                         session.setAttribute("validateFlag", "true");                         chain.doFilter(request, response);                     }else{                         request.getRequestDispatcher("/jsp/password_validate.jsp").forward(request, response);                     }                 }         }    }}
0 0
原创粉丝点击