You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在JSP页面调用SessionFactory时出现NullPointerException问题

问题原因及解决方案

报错原因

你遇到的NullPointerException是因为手动创建的QuestionService对象不受Spring容器管理:

  • 在JSP里用new QuestionService()实例化的对象,Spring不会对其进行@Autowired依赖注入,所以sessionFactory始终为null,调用openSession()时触发空指针异常。
  • 其他类能正常调用,是因为那些类本身是Spring管理的Bean(标注了@Service/@Controller等注解),Spring会自动为它们完成依赖注入。

解决方案

方案1:改用MVC架构(推荐)

遵循Spring MVC规范,通过Controller层调用Service,再将数据传递到JSP展示,避免在JSP中直接操作Service。

  1. 编写Controller类:
@Controller
public class QuestionController {
    @Autowired
    private QuestionService questionService;

    @RequestMapping("/queType")
    public String loadQueType(Model model) {
        List<Question> qList = questionService.getSubList();
        model.addAttribute("qList", qList);
        return "queType";
    }
}
  1. 修改JSP,用EL表达式获取数据:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<body>
    ${qList}
</body>
</html>

方案2:在JSP中获取Spring容器内的Bean(仅临时应急,不推荐)

如果必须在JSP中直接获取Service,可通过WebApplicationContext从Spring容器中获取已初始化好的Bean:

<%@page import="java.util.List"%>
<%@page import="com.guru.onlineexam.entity.Question"%>
<%@page import="com.guru.onlineexam.service.QuestionService"%>
<%@page import="org.springframework.web.context.WebApplicationContext"%>
<%@page import="org.springframework.web.context.support.WebApplicationContextUtils"%>
<%
    WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
    QuestionService qs = ctx.getBean(QuestionService.class);
    List<Question> qList = qs.getSubList();
    out.println(qList);
%>

额外注意点

你的getSubList()方法中,HQL语句SELECT DISTINCT que_subject FROM Question查询的是单个字段(假设为字符串类型),但返回类型声明为List<Question>,会触发类型转换异常,建议修正为:

public List<String> getSubList() {
    Session session = sessionFactory.openSession();
    String query = "SELECT DISTINCT que_subject FROM Question";
    Query q = session.createQuery(query, String.class);
    List<String> sublist = q.getResultList();
    session.close(); // 记得关闭Session避免资源泄漏
    return sublist;
}

内容的提问来源于stack exchange,提问作者user8265953

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 23:05:24