Servlet HTTP 500 - NullPointerException

use*_*441 0 java

我刚刚开始使用J2E.

NullPointerException排队了:

if (!userName.equals("") && userName != null)
Run Code Online (Sandbox Code Playgroud)

当我像这样运行服务器:

http://localhost:8080/SimpleServletProject/SimpleServletPath?name=test
Run Code Online (Sandbox Code Playgroud)

它完美地运作.但不接受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));
}}
Run Code Online (Sandbox Code Playgroud)

Tar*_*lah 12

if (!userName.equals("") && userName != null)
Run Code Online (Sandbox Code Playgroud)

应该

if (userName != null &&!userName.equals(""))
Run Code Online (Sandbox Code Playgroud)

因为首先您将需要检查null.So如果username = nullJava将使用短路并且不检查第二个条件.