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>
原文地址:https://www.cnblogs.com/tianhengblogs/p/5337689.html