HttpSession.getAttribute返回null触发Object.toString空指针异常
问题修复方案
错误根因
你遇到的Cannot invoke "Object.toString()" because the return value of "javax.servlet.http.HttpSession.getAttribute(String)" is null报错,本质是session中存储的uname属性为null,后续读取该属性直接调用toString()触发了空指针,具体有三个直接诱因:
- JSP表单使用
post方式提交,但你的Servlet只实现了doGet方法,post请求无法被正确处理,导致userName参数取值为null,直接存入了session - 没有对
userName参数做非空校验,即使用户空提交也会把null存入session - 后续读取
uname属性的代码没有先判空就直接调用toString()方法
修复步骤
1. 统一请求处理逻辑
两种方案二选一即可:
- 修改JSP表单的method属性为
get - 或者在Servlet中新增
doPost方法,复用doGet逻辑:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); }
2. 增加参数非空校验
修改doGet方法的参数处理逻辑,避免null值存入session:
public void doGet(HttpServletRequest request, HttpServletResponse response) { try{ response.setContentType("text/html"); PrintWriter out = response.getWriter(); String n=request.getParameter("userName"); // 新增参数校验 if(n == null || n.trim().isEmpty()){ out.print("请输入有效的用户名"); out.close(); return; } out.print("Welcome "+n); HttpSession session=request.getSession(); session.setAttribute("uname",n); out.close(); }catch(Exception e){ System.out.println(e); } }
3. 读取session属性前判空
后续所有调用session.getAttribute("uname")的位置,都先判断返回值是否为null再调用方法:
Object unameObj = session.getAttribute("uname"); if(unameObj != null){ String uname = unameObj.toString(); // 后续正常业务逻辑 }else{ // 处理未登录或session失效场景,比如跳转到登录页 }
内容的提问来源于stack exchange,提问作者Shubham
相关产品推荐
相关产品推荐

