servlet出现405错误

Servlet出现405错误

1.问题现象

使用url访问时,发现出现了405错误

2.问题原因

先查看对应的doGet方法,发现调用了父类的doGet()方法

 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws                             ServletException, IOException {
        resp.setContentType("text/html;charset=UTF-8");
        super.doGet(req,resp);
        PrintWriter out = resp.getWriter();
        try {
            out.println("<html>");
            out.println("<head>");
            out.println("<title>MyFirstServlet</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<h2>Welcome to my servlet我的我的</h2>");
            out.println("</body>");
            out.println("</html>");
        } finally {
            out.close();
        }
    }

进入父类的doGet()方法

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws                              ServletException, IOException {
        String msg = lStrings.getString("http.method_get_not_supported");
        this.sendMethodNotAllowed(req, resp, msg);
    }

父类的doGet()方法主要是调用了一个方法——sendMethodNotAllowed()方法,进入此方法

private void sendMethodNotAllowed(HttpServletRequest req, HttpServletResponse resp, String msg) throws IOException {
        String protocol = req.getProtocol();
        if (protocol.length() != 0 && !protocol.endsWith("0.9") && !protocol.endsWith("1.0")) {
            resp.sendError(405, msg);
        } else {
            resp.sendError(400, msg);
        }

    }

发现此方法调用了getProtocol()方法来获取协议的名称并判断版本号,最后调用sendError()方法来在页面中显示405错误或者400错误

3.解决方法

把调用的父类的doGet()方法删除

posted @ 2022-05-16 15:42  zeliCouer  阅读(284)  评论(0)    收藏  举报