• 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>
  • 相关阅读:
    测试本地node包
    webpack4+react多页面架构
    身为前端开发工程师,你需要了解的搜索引擎优化SEO.
    代码改变世界 | 如何封装一个简单的 Koa
    云计算系统測试之技术概念
    Cocos2d-x3.0 从代码中获取cocostudio编辑的UI控件
    Spring使用HibernateDaoSupport操作数据
    gitlab一键安装 笔记
    【TCP/IP】IP路由选择
    ios网络学习------3 用非代理方法实现异步post请求
  • 原文地址:https://www.cnblogs.com/tianhengblogs/p/5337689.html
Copyright © 2020-2023  润新知