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

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

在使用spring框架的过程中,受益于Spring框架中Bean的自动注入的方便,同时在JSP中需要使用到service层中的对象的时候,因为在service层都有dao层的自动注入,所以若是在JSP中直接使用如:

 

[java] view plain copy

 print?

  1. ServiceUser su = new ServiceUser();  

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

 

 

[java] view plain copy

 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这个对象再对数据库进行访问就不会再报空指针异常了。

 

转载于:https://my.oschina.net/u/2357525/blog/809657

你可能感兴趣的:(Spring MVC 在JSP中获取service层的Bean对象)