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

JSP中SendRedirect()失效并抛出NullPointerException问题求助

解决JSP中session获取UserBean为null时跳转失效引发的空指针异常

问题原因

response.sendRedirect()仅向浏览器发送重定向响应头,但当前JSP页面的剩余代码会继续执行。即使user为null,后续获取user.getName()、user.getId()等属性的代码仍会被执行,直接触发NullPointerException。

修复方案

在调用sendRedirect()后,立即添加return语句终止当前页面的代码执行,阻止后续逻辑运行。

修改后的跳转逻辑代码:

<%
UserBean user = (UserBean) session.getAttribute("user_details");
if (user == null) {
    response.sendRedirect("login.jsp");
    System.out.println(request.getContextPath());
    return; // 终止后续代码执行,避免空指针
}
%>

更规范的优化方案(推荐)

尽量避免在JSP中使用脚本代码,改用JSTL标签库和EL表达式,既能简化代码,又能避免空指针问题:

  1. 先引入JSTL核心标签库:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
  1. 重定向判断:
<c:if test="${empty user_details}">
    <c:redirect url="login.jsp" />
</c:if>
  1. 属性获取(EL表达式在对象为null时会输出空字符串,不会抛出异常):
<tr>
    <td>Name</td>
    <td>${user_details.name}</td>
</tr>
<tr>
    <td>About</td>
    <td>${user_details.about}</td>
</tr>
<tr>
    <td>Email</td>
    <td>${user_details.email}</td>
</tr>
<tr>
    <td>Gender</td>
    <td>${user_details.gender}</td>
</tr>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 00:56:01