【问题标题】:java.lang.NullPointerException in servlet error 500servlet 错误 500 中的 java.lang.NullPointerException
【发布时间】:2017-11-16 22:25:11
【问题描述】:

当我运行我的 Servlet 时,我得到了这个错误: java.lang.NullPointerException 请我尝试了很多解决方案,但它没有工作它是简单的代码

public LoginServlett() {
    super();

}

protected void doGet(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();


    String name = request.getParameter("UserName");
    String pass = request.getParameter("Password"); 

    RequestDispatcher d=null;

    if (name.contentEquals("Gestionnaire") && pass.contentEquals("1234")) {
         HttpSession session;
         session =request.getSession(true );
          d =request.getRequestDispatcher("/EspaceGestionnaire.html");
         session. setAttribute("NomSauvegardé" ,name);
    }

    else {
         d = request.getRequestDispatcher("/Authentification.html");
        d.forward(request, response);

    } 
}

protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
}

}

【问题讨论】:

  • 它在什么时候抱怨 NPE?日志应该会告诉你。我的猜测是其中一个文件不存在
  • NullPointerException 如此普遍,JEE 机器如此之大,它可以是任何东西。尝试更深入地挖掘,试验代码,然后发布完整的堆栈跟踪。
  • 日志文件存在于 C:\Users\pc\JEE-workspace\AgenceLocations\build\classes\LoginServlett 中的 LoginServlett.class the others /EspaceGestionnaire &/Authentification in C:\Users\pc\JEE -workspace\AgenceLocations\WebContent

标签: servlets jakarta-ee nullpointerexception dispatcher


【解决方案1】:

如果未设置用户名和密码参数,则代码中会抛出 NPE。如果未设置,则 userpass 变量将为 null,并且当对其调用 contentEquals 方法时,将引发 NPE。

执行此操作的一种方法是反转相等性检查,以便在您要检查的字符串上调用该操作:

if ("Gestionnaire".contentEquals(name) && "1234".contentEquals(pass)) {

这将在不抛出 NPE 的情况下执行您的代码的意图。

虽然如果您通过 Internet 发送密码,使用 POST 比使用 GET 更好。对于 Java EE 安全,还有新的安全 API (https://javaee.github.io/security-spec/)

【讨论】:

    猜你喜欢
    • 2012-03-05
    • 1970-01-01
    • 1970-01-01
    • 2017-01-16
    • 1970-01-01
    • 2015-12-05
    • 2014-12-24
    • 1970-01-01
    • 2014-03-21
    相关资源
    最近更新 更多