繁体   English   中英

Servlet RequestDispatcher不转发

[英]Servlet RequestDispatcher is not forwarding

我正在学习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);
   }
}

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>

我的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>

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

type - Status report
message - Projectname/file.jsp
description - The requested resource is not available.

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

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

RequestDispatcher aDispatcher = request.getRequestDispatcher("/file.jsp");

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

或尝试

RequestDispatcher aDispatcher = request.getRequestDispatcher("/WEB-INF/file.jsp");

如果jsp文件在WEB-INF文件夹下。

项目结构:

WebContent
       |
       |__file.jsp
       |
       |__WEB-INF
              |
              |__file.jsp
              |__web.xml

阅读Java Web应用程序中使用的WEB-INF是什么?

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM