首页 > 其他 > 详细

Servlet里面一调用Dao里的某个方法

时间:2019-05-31 18:09:26      阅读:348      评论:0      收藏:0      [点我收藏+]

背景:

这几天,由于项目集成的需要,我要在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中的方法。

 

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

技术分享图片

Servlet里面一调用Dao里的某个方法

原文:https://www.cnblogs.com/zhangliang88/p/10956621.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!