java - 如何在 JSP 错误页面中显示请求的 URL?

标签 java jsp servlets custom-error-pages

在错误页面中,我想显示用户请求的 URL。

在我的 web.xml 中:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.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"
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
                            http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
        id="WebApp_ID"
        version="3.0">

    <display-name>MyStuff</display-name>

    <error-page>
        <error-code>404</error-code>
        <location>/WEB-INF/error-404.jsp</location>
    </error-page>

</web-app>

这将转发到 error-404.jsp,这是该文件的内容:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Page Not found</title>
</head>
<body>
    <p align="center">
    <%
        out.println("Requested resource: " + request.getRequestURL()+ " not found");
    %>
</body>
</html>


问题是 request.getRequestURL() 需要更改,但不知道要搜索什么的关键字。

当我为 http://localhost:8080/MyStuff 启动浏览器时,出现以下错误:

请求的资源:http://localhost:8080/MyStuff/WEB-INF/error-404.jsp 未找到

如何解决?

最佳答案

这是一个简单的 JSP 错误页面示例,它显示错误代码和所请求页面的 URL:

404.jsp:

<%@ page language="java" isErrorPage="true" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
    <title>Error page</title>
    <meta charset="utf-8">
</head>
<body>
    <button onclick="history.back()">Back to Previous Page</button>
    <h1>404 Page Not Found.</h1>
    <br />
    <p><b>Error code:</b> ${pageContext.errorData.statusCode}</p>
    <p><b>Request URI:</b> ${pageContext.request.scheme}://${header.host}${pageContext.errorData.requestURI}</p>
    <br />
</body>
</html>

有用的阅读:

附言
强烈建议不要在 JSP 中使用 scriptlet。阅读this post .

关于java - 如何在 JSP 错误页面中显示请求的 URL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14300404/

相关文章:

javascript - 将值从 Servlet 传递到 JSP 中的 onload JavaScript 函数

java - 在jsp中下载图片: Illegalstateexception: getwriter() has already been called for this response

java - Chrome 浏览器和 Java 消息传递

java tomcat utf-8编码问题

java - 从一个 Web 应用程序到另一个 Web 应用程序获取 cookie 或 session

java - 根据 Spring MVC 中服务的结果验证单个字段

java - Servlet 中的 iText PDF

java - 如何从 Java Android 中的按钮单击调用 Location 方法?

java - JSF 导航参数依赖性

java - 解析命令行并将其更改为 Char 或 Boolean