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

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上下文的一个类
第三个不就是和第二个类似吗(我觉得)^_^

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值