jsp 开发之servlet中调用注入spring管理的dao
我们用spring的依赖注入可以将dao注入到action中,然后我们就可以直接调用了dao中的方法了,可是servlet不是由spring容器管理,所以在servlet中不能注入dao类,也就不能用dao中的方法。
下面是实现方法:
private userdao userdao;
public void init() throws servletexception {
super.init();
servletcontext servletcontext = this.getservletcontext();
webapplicationcontext ctx = webapplicationcontextutils.getwebapplicationcontext(servletcontext);
userdao = (userdao)ctx.getbean("userdao");
}
在servlet中加入私有变量userdao,然后在servlet的init()方法中初始化一下即可用。
public userdao getuserdao() {
return userdao;
}
public void setuserdao(userdao userdao) {
this.userdao = userdao;
}
还要加get set方法,(去掉这个的情况没有测试)
以后就可以随意在servlet中调用dao了,耶!
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
【说明】:本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!