web.xml 文件配置通用的错误页面

avatar 2017年07月10日13:51:33 1 3036 views
博主分享免费Java教学视频,B站账号:Java刘哥
承接上文,使用errorPage属性指定错误页面 在 Jsp 程序中,如果为每个页面都指定一个错误页面,这样的做法显然很繁琐。这时,可以在 web.xml 文件中使用 <error-page> 元素为整个 Web 应用程序设置错误处理页面,具体示例如下所示:
  1. <error-page>
  2.     <error-code>404</error-code>
  3.     <location>/404.jsp</location>
  4. </error-page>
  5. <error-page>
  6.     <error-code>500</error-code>
  7.     <location>/500.jsp</location>
  8. </error-page>
上面的示例代码用于处理所有 404 和 500 状态码的页面 接下来,我们来看这个简单案例 (1) 新建 page.jsp
  1. <%@ page language="java" contentType="text/html; charset=UTF-8"
  2.     pageEncoding="UTF-8" %>
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  4. <html>
  5. <head>
  6. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  7. <title>Insert title here</title>
  8. </head>
  9. <body>
  10.     <%
  11.         int a = 1/0;
  12.     %>
  13. </body>
  14. </html>
(2)分别新建 404.jsp 和 500.jsp 400.jsp
  1. <%@ page language="java" contentType="text/html; charset=UTF-8"
  2.     pageEncoding="UTF-8"%>
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  4. <html>
  5. <head>
  6. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  7. <title>Insert title here</title>
  8. </head>
  9. <body>
  10. <h2>通用500错误页面</h2>
  11. </body>
  12. </html>
500.jsp
  1. <%@ page language="java" contentType="text/html; charset=UTF-8"
  2.     pageEncoding="UTF-8"%>
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  4. <html>
  5. <head>
  6. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  7. <title>Insert title here</title>
  8. </head>
  9. <body>
  10. <h2>通用500错误页面</h2>
  11. </body>
  12. </html>
(3)启动 Tomcat,打开浏览器 在地址栏输入:http://localhost:8080/JspDemo/page.jsp   需要注意的是: ① 如果设置了某个页面的 errorPage 属性,那么在 web.xml 文件设置的异常错误处理将对该处理页面不起作用。 ② 在 IE 浏览器测试的时候,页面可能会无法显示错误信息,这时,可以单击“IE工具”-->"Internet选项"-->“高级”命令,取消勾选选项“显示友好 http 错误提示”复选框。 本文链接:https://liuyanzhao.com/5125.html
  • 微信
  • 交流学习,有偿服务
  • weinxin
  • 博客/Java交流群
  • 资源分享,问题解决,技术交流。群号:590480292
  • weinxin
avatar

发表评论

avatar 登录者:匿名
匿名评论,评论回复后会有邮件通知

  

已通过评论:0   待审核评论数:0