Jsp中如何调用Spring管理的bean
首先通报我的环境是Myeclipse6.0.1+mysql5,工程使用Struts1.2+Spring2+Hibernate3.1
我想要在JSP页面中通过调用JAVABEAN显示数据库中的内容,JAVABEAN查询数据库时使用Hibernate的DAO
JSP中调用如下:
<jsp:useBean class="com.flear.beans.Company" id="com" scope="request">
<% out.print(com.listAllCheckedCompany()); %>
</jsp:useBean>
JAVABEAN如下:
public class Article {
private JfArticlesDAO articleDAO;
private JfArticles article;
//getter,setter......省略
public String listAllArticle()
{
String str="";
List<Article> articleList=articleDAO.findAll();
for(Iterator ai=articleList.iterator();ai.hasNext();)
{
article=(JfArticles)ai.next();
str+=article.getAContent();
}
return str;
}
}
applicationContext中配置如下:
<bean id="JfArticlesDAO" class="com.flear.DAO.JfArticlesDAO">
<property name="sessionFactory">
<ref bean="sessionFactory" />
</property>
</bean>
<bean id="JfArticles" class="com.flear.vo.JfArticles" abstract="false"
lazy-init="default" autowire="default"
dependency-check="default">
</bean>
<bean id="Article" class="com.flear.beans.Article">
<property name="articleDAO" ref="JfArticlesDAO">
</property>
<property name="article" ref="JfArticles"></property>
</bean>
然后测试时报异常如下:
java.lang.NullPointerException com.flear.beans.Article.listAllArticle(Article.java:52)
org.apache.jsp.index_jsp._jspService(index_jsp.java:175)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:387)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:320)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:266)
javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFilter.java:96)
我自己进行了调试,异常是因为调用JAVABEAN中的article.listAllArticle()时,JAVABEAN中的articleDAO和article均为null,应该是没有调用spring注入的bean,但是我不知道该如何改正,请高手指教
------解决方案--------------------
用了spring,它负责对象的创建和注入,就是它帮你管理对象,而你在页面上使用了<jsp:useBean />来创建bean,即相当于new XXX(),这样bean中的很多属性当然为null,所以报错