【问题标题】:Cannot access jsp page via servlet无法通过 servlet 访问 jsp 页面
【发布时间】:2016-06-28 00:43:11
【问题描述】:

src/main/java/com.company.HelloWorldServlet.java

public class HelloWorldServlet extends HttpServlet {
    public void doGet(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {
        String message = "hello";
        req.setAttribute("message", message);
        req.getRequestDispatcher("/WEB-INF/page.jsp").forward(req, res);
    }
}

web/WEB-INF/page.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Hello world Servlet + JSP</title>
</head>
<body>
<p>Data from Servlet: ${message}</p>
</body>
</html>

web/WEB-INF/web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <display-name>HelloWorldServlet</display-name>
    <servlet>
        <servlet-name>HelloWorld</servlet-name>
        <servlet-class>com.company.HelloWorldServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>HelloWorld</servlet-name>
        <url-pattern>/helloworld</url-pattern>
    </servlet-mapping>
</web-app>

应用程序正在本地主机上的 Tomcat7 服务器上运行。

访问http://localhost:8080/HelloWorldServlet/helloworld 会得到404 - /HelloWorldServlet/helloworld

访问http://localhost:8080/helloworld 会得到404 - /WEB-INF/page.jsp

为什么我的 .jsp 页面对 servlet 不可见?将 .jsp 文件放入 /web/ 也不会改变任何内容。

【问题讨论】:

  • 那么,您没有运行您认为正在运行的代码?您是否进行了完整的清理/重建/重新部署/重新启动/等?如果无效,让构建系统生成一个 WAR 文件,然后您使用 ZIP 工具检查该文件并检查 JSP 文件是否真的在您期望的位置。
  • @BalusC 我检查了 WAR 文件,但 JSP 文件确实不存在。我不得不将包含 JSP 的目录作为资源添加到 Maven 的 pom.xml 文件中。现在它工作正常。谢谢你的提示!

标签: jsp servlets http-status-code-404 requestdispatcher


【解决方案1】:

我添加了 pom.xml 条目来告诉 Maven 资源和配置文件在哪里,从而解决了问题。

       <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-war-plugin</artifactId>
            <configuration>
                <webXml>src/main/webapp/WEB-INF/web.xml</webXml>
            </configuration>
        </plugin>
    </plugins>
    <resources>
        <resource>
            <directory>src/main/webapp</directory>
        </resource>
    </resources>

【讨论】:

    猜你喜欢
    • 2023-03-05
    • 2016-02-24
    • 1970-01-01
    • 1970-01-01
    • 2013-02-06
    • 2011-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多