背景:
这几天,由于项目集成的需要,我要在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 {
..