Spring MVC 在JSP中获取service层的Bean对象

在使用spring框架的过程当中,受益于Spring框架中Bean的自动注入的方便,同时在JSP中须要使用到service层中的对象的时候,由于在service层都有dao层的自动注入,因此如果在JSP中直接使用如:java

 

[java] view plain copyweb

 print?spring

  1. ServiceUser su = new ServiceUser();  

会出现空指针的状况,这种空指针是因为在ServiceUser中使用到了DaoUser的自动注入,也就是说,直接在JSP页面中实例化一个ServiceUser对象,其中的DaoUser是没有被注入的。为了解决这种情况,想到Spring这个容器在Web程序运行起来后,其中的全部对象都已经被装入到了ApplicationContext对象(即Spring容器)中,能不能直接从容器中把serviceUser这个Bean取出来呢?答案是确定的,以下:数据库

 

 

[java] view plain copyapp

 print?框架

  1. <%@page import="org.springframework.web.context.support.WebApplicationContextUtils"%>  
  2. <%@page import="org.springframework.context.ApplicationContext"%>  
  3.   
  4. /** 从Spring容器中获取 ServiceUser这个Bean对象 */  
  5.     ServletContext sc = this.getServletContext();  
  6.     ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(sc);  
  7.     ServiceUser serviceuser = (ServiceUser) ac.getBean("serviceUser");// 这里就能够直接取出所须要的service层中的Bean了  


这样,在后面使用serviceuser这个对象再对数据库进行访问就不会再报空指针异常了。this

相关文章
相关标签/搜索