2019/4/2
问题描述
在SpringWeb配置好applicationContext相关配置文件后,进入jsp页面通过连接访问servlet中的某个值(本项目中访问的是“studentService”),结果发生了如下错误:
java.lang.NullPointerException
servlet.QueryStudentByIdServlet.doGet(QueryStudentByIdServlet.java:45)
解决思路
通过Debug发现,在查询是的Servlet类的doGet()中,发现了
studentService = null;
然而,在 Servlet类的setStudentService(IStudentService studentService)中,通过Debug发现
studentService= service.impl.StudentServiceImpl@3c35ded3
这就引发了思考:为什么明明给studentService赋值了,但是查询时却引发了空指针呢?
以下是答案
1.首先在Servlet类的setStudentService(IStudentService studentService)中 studentService= service.impl.StudentServiceImpl@3c35ded3是因为在SpringIoc容器中,通过bean属性给studentService一个值。因此,此时有值的studentService是在SpingIoc容器中的!!!
2.其次,在通过jsp查询studentService是,是通过 a href="QueryStudentByIdServlet"标签访问的。这代表着查询时通过servlet访问是Tomcat容器中的studentService值!!!此时Tomcat容器中的studentService并没有赋值,所以引发了空指针!
3.根据以上,可以在Servlet类中加如Init()方法,来构建Tomcat容器和SpingIoc容器的桥梁,使Servlet类可以访问SpingIoc容器。
解决方法
在Servlet类中加入Init方法:
public void init() throws ServletException {
//Web项目获取Spring上下文对象context
ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
//当前在Servlet中,通过getBean获取SpringIoc容器中的bean对象
studentService = (IStudentService)context.getBean("studentService");
}