【问题标题】:Java Servlet java.lang.NullPointerException at doGet()Java Servlet java.lang.NullPointerException 在 doGet()
【发布时间】:2021-06-18 03:20:54
【问题描述】:

我有一个 HTTP 500 - java servlet 的内部服务器错误。而且我没有在论坛上为我的案例找到解决方案。我正在使用 IntelliJ Ultimate 2020.3 和 Apache Tomcat Server 9.0.43。这是我的项目文件结构和我的代码。我一直在寻找解决方案 3 个小时。拜托,我需要帮助。

servlet 类

package com.sdzee.servlets;

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 java.io.IOException;

@WebServlet(name="Test",value="/test2")
public class Test extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.getServletContext().getRequestDispatcher("/../../main/webapp/test.jsp").forward(req,resp);
    }

}

test.jsp 文件

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Test</title>
</head>
<body>
<p>JSP test</p>
</body>
</html>

web.xml 中的 servlet 定义

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <servlet>
        <servlet-name>Test</servlet-name>
        <servlet-class>com.sdzee.servlets.Test</servlet-class>

        <init-param>
            <param-name>Auteur</param-name>
            <param-value>Moi</param-value>
        </init-param>

    </servlet>
    <servlet-mapping>
        <servlet-name>Test</servlet-name>
        <url-pattern>/test2</url-pattern>
    </servlet-mapping>
</web-app>

结果:

【问题讨论】:

  • main 目录在运行时不存在。查看 WAR 文件中的实际内容。

标签: java jsp intellij-idea servlets tomcat9


【解决方案1】:

我认为 getRequestDispatcher("/../../main/webapp/test.jsp") 应该是 getRequestDispatcher("/test.jsp")

【讨论】:

  • 是的,它有效,非常感谢。但我想了解为什么只是 ("/test.jsp") 作为文件不在同一个文件夹中。
  • 参数是url,不是文件路径。您也可以浏览http://localhost:8080/test.jsp 并打开 jsp 而无需通过您的 servlet。
猜你喜欢
  • 2014-05-23
  • 1970-01-01
  • 1970-01-01
  • 2012-11-12
  • 2011-07-09
  • 1970-01-01
  • 1970-01-01
  • 2011-08-18
  • 2016-02-22
相关资源
最近更新 更多