Servlet RequestDispatcher 未转发

Ken*_*nny 5 java eclipse jsp tomcat servlets

我正在学习 Java Servlets 和 JSP。

我有以下代码:

HelloServlet.jsp

public class HelloServlet extends HttpServlet {
    private static final long serialVersionUID=1;

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

        response.setContentType("text/html");
        response.setCharacterEncoding("utf-8);

        RequestDispatcher aDispatcher = request.getRequestDispatcher("file.jsp");
        aDispatcher.forward(request,response);
   }
}
Run Code Online (Sandbox Code Playgroud)

file.jsp

<!DOCTYPE html>
<%@ page language="java" contentType="text/html; charset=UTF-8" 
   pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<html>
    <head>
        <title>First JSP</title>
    </head>
    <body>
        Hello!!
    </body>
</html>
Run Code Online (Sandbox Code Playgroud)

我的web.xml看起来像这样:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://w3.org/2001/XMLSchema-instance" 
   xmlns="http://java.sun.com/xml/ns/javaee" 
   xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
   xmlns:schemaLocation="http://java.sun.som/xml/ns/javaee 
      http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
   id="WebApp_ID" version="2.5">

    <display-name>Hello</display-name>

    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

    <servlet>
        <description></description>
        <display-name>Hello Servlet</display-name>
        <servlet-name>hello</servlet-name>
        <servlet-class>be.howest.HelloServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>hello</servlet-name>
        <url-pattern>/urlpattern</url-pattern>
    </servlet-mapping>

</web-app>
Run Code Online (Sandbox Code Playgroud)

当我在 Tomcat 上运行该文件时,出现以下错误:
HTTP Status 404 - /Projectname/file.jsp

type - Status report
message - Projectname/file.jsp
description - The requested resource is not available.
Run Code Online (Sandbox Code Playgroud)

我做错了什么?因为我自己找不到解决方案

Bra*_*raj 4

尝试使用前缀斜杠,如下所示

RequestDispatcher aDispatcher = request.getRequestDispatcher("/file.jsp");
Run Code Online (Sandbox Code Playgroud)

如果 jsp 文件直接存在于 webapp 文件夹下。

或尝试

RequestDispatcher aDispatcher = request.getRequestDispatcher("/WEB-INF/file.jsp");
Run Code Online (Sandbox Code Playgroud)

如果jsp文件位于WEB-INF文件夹下。

项目结构:

WebContent
       |
       |__file.jsp
       |
       |__WEB-INF
              |
              |__file.jsp
              |__web.xml
Run Code Online (Sandbox Code Playgroud)

阅读WEB-INF 在 Java Web 应用程序中有何用途?

如果您不想直接访问此 JSP 文件,则将其放在WEB-INF无法公开访问的文件夹中,这对于受限资源来说是更安全的方式。

放置在 WEB-INF 下的 JSP 文件不能通过简单地单击 URL 直接访问,在这种情况下,它只能由应用程序访问。

  • 我已将其放在“WebContent”文件夹下,现在它可以工作了。现在这是一个愚蠢的问题:( (2认同)