gpt4 book ai didi

java - Servlet HTTP 500 - NullPointerException

转载 作者:行者123 更新时间:2023-12-01 06:35:03 25 4
gpt4 key购买 nike

我刚刚开始接触 J2E。

我在该行中遇到了 NullPointerException:

if (!userName.equals("") && userName != null)

当我像这样运行服务器时:

http://localhost:8080/SimpleServletProject/SimpleServletPath?name=test

它工作得很好。但不接受 null。

完整代码:

package org.mojservlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


@WebServlet("/SimpleServletPath")
public class SimpleServlet extends HttpServlet {
private static final long serialVersionUID = 1L;


protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("get method");
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
String userName = request.getParameter("name");
HttpSession session = request.getSession();
ServletContext context = request.getServletContext();
if (!userName.equals("") && userName != null){
session.setAttribute("savedUserName", userName);
context.setAttribute("savedUserName", userName);
}
writer.println("Request parameter has username as " + userName);
writer.println(" Session paramter has username as " + (String) session.getAttribute("savedUserName"));
writer.println(" context is " + (String) context.getAttribute(userName));
}}

最佳答案

if (!userName.equals("") && userName != null)

应该是

if (userName != null &&!userName.equals(""))

因为首先您需要检查 null。因此,如果 username = null 那么 Java 将使用 short circuit并且不会检查第二个条件。

关于java - Servlet HTTP 500 - NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20922095/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com