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
- Spring学习笔记-在Filter中获取SpingIOC容器
- 在filter中获取spring容器中的bean对象
- 在servlet中或者在filter中获取spring容器中的bean
- 如何在filter中拿到spring容器
- 在Servlet Filter中使用Spring容器
- 在Servlet Filter中使用Spring容器
- Spring学习笔记四: 从Spring容器中获取Bean
- 如何在监听器中获取spring容器
- 在方法中获取spring容器
- 在web容器中获取spring容器对象
- 在web容器中获取spring容器中的bean对象
- 框架类---spring---Filter中获取Spring容器中的bean对象
- 在servlet、filter、Taglib中获取Spring Bean
- Spring学习笔记-Spring容器
- 在Bean中获取Spring容器中的各种组件
- 如何在非注入类中,获取spring容器
- 在Servlet(或者Filter,或者Listener)中使用spring的IOC容器
- 在Servlet(或者Filter,或者Listener)中使用spring的IOC容器
- CYC-数据库的运用
- 【Android应用开发技术:网络通信】Socket套接字
- HDU 5491 The next(2015 ACM/ICPC Asia Regional Hefei Online )(贪心)
- spark streaming updateStateByKey 用法
- libevent学习笔记二:使用evdns_getaddrinfo()的例子
- Spring学习笔记-在Filter中获取SpingIOC容器
- Improved Noise reference implementation
- Struts2六、为应用指定多个配置文件
- C++ primer 5 笔记4 chapter 4 表达式
- JS中语句使用的注意事项
- LockBox - RSA
- Swift 2.0中的数据类型
- Exporting C++ classes from a DLL
- SQL Server学习记录之递增生成注册ID号