zoukankan      html  css  js  c++  java
  • Servlet里面一调用Dao里的某个方法

    背景:

    这几天,由于项目集成的需要,我要在doFilter里调用dao层里的某些方法,可是总之报空指针,只要调用那个dao方法,就报错误。很是纳闷,网上查找了各种原因,终于让我给突破了,看来还是Java基础掌握的不够呀!

    代码:

    在servlet中加入私有变量UserDao,然后在servlet的init()方法中初始化一下即可用。

    private UserDao userDao;

    public void init(FilterConfig filterConfig) throws ServletException {
    ServletContext sc = filterConfig.getServletContext();
    XmlWebApplicationContext cxt = (XmlWebApplicationContext)WebApplicationContextUtils.getWebApplicationContext(sc);
    if(cxt != null && cxt.getBean("userDao") != null && userDao == null)
    userDao = (UserDao) cxt.getBean("userDao");
    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

    ...............

    //下面只展示调用的方法

    DashboardUser dashboardUser = userDao.getOauthUserByLoginName(oauthUserCode);
    String userId = dashboardUser.getUserId();
    String username = dashboardUser.getUserName();
    String loginname = dashboardUser.getLoginName();
    String password = dashboardUser.getUserPassword();
    boolean enabled = true;
    User user = new User(loginname, password, enabled, true, true, true, AuthorityUtils.NO_AUTHORITIES);
    user.setUserId(userId);
    user.setName(username);
    SecurityContext context = SecurityContextHolder.getContext();
    context.setAuthentication(new ShareAuthenticationToken(user));
    hsr.getSession().setAttribute("SPRING_SECURITY_CONTEXT", context);

    ..............

    }

    总结一下:

    在servlet里面想调用接口实现类,结果一直报空指针异常。不能new 接口实现类

    我们用spring的依赖注入可以将dao注入到action中,然后我们就可以直接调用了dao中的方法了,可是servlet不是由spring容器管理,所以在servlet中不能注入dao类,也就不能用dao中的方法。

    如果这篇文章对您有所帮助,请随便打赏一下作为鼓励,我会再接再厉的!!!

  • 相关阅读:
    二叉树的遍历(递归,迭代,Morris遍历)
    1003. Emergency
    1002. A+B for Polynomials
    设计模式6——创建型模式之原型模式
    设计模式5——创建型模式之建造者模式
    设计模式4——创建型模式之单例模式
    设计模式3——创建型模式之抽象工厂模式
    设计模式2——创建型模式之工厂方法模式
    设计模式1——创建型模式之简单工厂模式
    设计模式六大原则
  • 原文地址:https://www.cnblogs.com/zhangliang88/p/10956621.html
Copyright © 2011-2022 走看看