我正在学习 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);
}
}
文件.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 状态 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
阅读What is WEB-INF used for in a Java web application?
如果您不想直接访问此 JSP 文件,则将其放在无法公开访问的 WEB-INF
文件夹中,这是对受限资源更安全的方式。
放置在 WEB-INF 下的 JSP 文件无法通过简单地点击 URL 直接访问,在这种情况下,它只能由应用程序访问。
关于java - Servlet RequestDispatcher 不转发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24167274/