我刚刚开始使用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));
}}
答案 0 :(得分:12)
if (!userName.equals("") && userName != null)
应该是
if (userName != null &&!userName.equals(""))
因为首先你需要检查null。如果username = null
那么Java将使用short circuit并且不会检查第二个条件。