背景:
這幾天,由於項目集成的需要,我要在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中的方法。
如果這篇文章對您有所幫助,請隨便打賞一下作為鼓勵,我會再接再厲的!!!

