Java EE Servlet读取txt存储账号密码登录始终跳转失败页问题排查
问题根因
- 核心故障点:你在
doGet方法中先调用response.getWriter()获取了响应输出流,还向输出流写入了错误提示内容,此时响应已经被提交,后续再执行sendRedirect重定向会违反Servlet规范,抛出未捕获的IllegalStateException,导致重定向逻辑异常,最终跳转失败。 - 潜在故障点1:读取
accounts.txt拆分凭证时未做去空格处理,若文件行首尾、逗号前后存在空格、换行符等不可见字符,会导致Map中存储的凭证和用户提交的内容不匹配。 - 潜在故障点2:未校验
accounts.txt是否正常加载,若文件存放位置错误,getResourceAsStream返回null时Map中无任何凭证数据,永远校验失败。 - 潜在故障点3:重定向使用相对路径,若应用配置了上下文路径,会导致跳转的页面路径错误。
修复方案
- 移除
doGet方法中所有PrintWriter相关代码,校验失败的提示放到fail.jsp中展示,避免提前提交响应,修改后的doGet核心逻辑如下:
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { String userEmail = request.getParameter("email"); String userPassword = request.getParameter("password"); boolean isValidUser = false; String password = credentialsPairs.get(userEmail); if (password != null && password.equals(userPassword)) { isValidUser = true; } if (isValidUser) { response.sendRedirect(request.getContextPath() + "/welcome.jsp"); } else { response.sendRedirect(request.getContextPath() + "/fail.jsp"); } }
- 修改
init方法中读取文件的逻辑,增加空行跳过、数组长度校验、去空格处理,避免格式错误导致的匹配失败:
while ((line = br.readLine()) != null) { line = line.trim(); // 跳过空行 if(line.isEmpty()) continue; String[] credentials = line.split(delimiter); // 跳过格式错误的行 if(credentials.length >= 2) { credentialsPairs.put(credentials[0].trim(), credentials[1].trim()); } }
- 确认
accounts.txt文件存放在项目的WEB-INF目录下,部署后Tomcat对应应用的WEB-INF目录下存在该文件。 - 可选优化:移除HelloServlet类上无用的
@WebServlet("/HelloServlet")注解,避免出现重复的Servlet映射。
内容的提问来源于stack exchange,提问作者Mohammed Hamdoon
相关产品推荐
相关产品推荐

