zoukankan      html  css  js  c++  java
  • Servlet------(声明式)异常处理

    Test.java

    其他方法不变,重写

    protected void service()方法
    public void init(ServletConfig config) throws ServletException {
            // Put your code here
            super.init(config);
        }
    
        @Override
        protected void service(HttpServletRequest req, HttpServletResponse res)
                throws ServletException, IOException {
            // TODO Auto-generated method stub
            //super.service(arg0, arg1);
            String method=req.getMethod();
            if(method.equals("POST")){
                doPost(req,res);
            }
            else if(method.equals("GET")){
                doGet(req,res);
            }
            
            res.setContentType("text/html;charset=gb2312");
            PrintWriter out=res.getWriter();
            
            Integer status_code=(Integer) req.getAttribute("javax.servlet.error.status_code");
            
            out.print("<html><head><title>错误处理页面</title></head>");
            out.print("<body>");
            
            switch(status_code){
            case 401:
                break;
            case 404:
                out.print("<h2>HTTP转态代码: "+status_code+"</h2><br>");
                out.print("您正在搜索的页面已删除<>br");
                break;
                default:
                    break;
            }
            out.print("</body>");
            out.print("</html>");
            out.close();
        }

    web.xml

    其他代码不变,加入下面代码

    <web-app>
    ........
    
    <error-page>
          <error-code>401</error-code>
          <location>/errorPage.jsp</location>
      </error-page>
      <error-page>
          <error-code>404</error-code>
          <location>/errorPage.jsp</location>
      </error-page>
    </web-app>

    errorPage.jsp

    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    <%
        String path = request.getContextPath();
        String basePath = request.getScheme() + "://"
                + request.getServerName() + ":" + request.getServerPort()
                + path + "/";
    %>
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
    <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'welcome.jsp' starting page</title>
    </head>
    
    <body>
        401,405错误处理页面
    </body>
    </html>
  • 相关阅读:
    oracle“记录被另一个用户锁住”
    Oracle CASE WHEN 用法介绍
    拥有机器人的人生会是怎样的体验?
    需求那么多,核心需求都从哪里来?
    一文读懂互联网及电商逻辑
    读书:《敏捷产品--不确定性的思维革命》
    读书:《超越感觉:批判性思考指南》一
    618啦,你的钱包又被盯上啦!
    产品经理如何开启上帝视角?
    我的产品经理价值观
  • 原文地址:https://www.cnblogs.com/tianhengblogs/p/5337689.html
Copyright © 2011-2022 走看看