S2SH中,JSP页面调用dao的方法

来源:互联网 发布:库卡机器人编程教材 编辑:程序博客网 时间:2024/06/07 13:56

S2SH项目中,在spring中 我们知道请求是从action进入,如果在JSP页面直接调用dao的方法会报空指针

异常
找了半天,终于找到了解决办法。
第一步:在JSP页面导入

<%@ page import= "org.springframework.context.ApplicationContext "%> <%@ page import= "org.springframework.web.context.support.WebApplicationContextUtils "%>

 

第二步:找到spring的bean

<%ApplicationContext ctx =WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext());ArticleService articleService = (ArticleService)ctx.getBean("articleImpl"); List ar = articleService.allReplyByDid(did); //就可以直接用里面的方法了%>

注意spring配置文件

<bean id="TArticleDAO" class="com.skycms.main.article.TArticleDAO"><property name="sessionFactory"><ref bean="sessionFactory" /></property></bean><bean id="articleImpl" class="com.skycms.main.article.ArticleImpl"><property name="articleDAO" ref="TArticleDAO"></property><property name="discussDAO" ref="TDiscussDAO"></property><property name="replyDAO" ref="TReplyDAO"></property></bean><bean id="article" class="com.skycms.main.article.ArticleAction"><property name="articleService" ref="articleImpl"></property></bean>


这样就可以了!

 

收集的一些东西:

一:
ApplicationContext   ctx   =   new   FileSystemXmlApplicationContext( "applicationContext.xml ");

二:
ApplicationContext   ctx   =   WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext());

三:
ServletContext   servletContext   =   request.getSession().getServletContext();      
WebApplicationContext   wac   =   WebApplicationContextUtils. getRequiredWebApplicationContext(servletContext);      


什么区别啊?

 

第一个是比较通用的获得spring上下文的一个类,它的参数是文件所在本地系统的路径,它不仅可以用于b/s的web应用程序,也可以应用于c/s的桌面程序,如果你在web应用中采用这种方式的话,没有指定配置文件的绝对路径,它默认是从tomcat/bin目录去加载(如果你用的tomcat作为你的web   server的话^_^)
第二个是web应用程序专用的一个获得spring上下文的一个类
第三个不就是和第二个类似吗(我觉得)^_^