HttpServlet을 구현하고 doGet, doPost를 자동 override 하면 405 에러가 난다고?

YJ KIM·2025년 3월 19일
0
post-thumbnail

HttpServlet을 IDE를 통해 구현하면 보통 자동 코드 생성을 사용하게 된다.

이때, HttpServlet이 내부에서 protected로 doGet(), doPost() 메소드를 미리 구현하고 있어 super.doGet() 과 같은 형태가 자동으로 호출된다.

실제로 코드를 자동 생성하면

@Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }

위와 같은 형태로 구현하게 되고, super.doPost(req, resp)가 호출된다.
📍 이때 super 호출 코드를 삭제하지 않으면 405 에러가 발생한다.

그 이유는 super.doGet, super.doPost 호출 때문이다.

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

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String protocol = req.getProtocol();
        String msg = lStrings.getString("http.method_post_not_supported");
        resp.sendError(this.getMethodNotSupportedCode(protocol), msg);
    }

실제 구현부를 디컴파일 해보면, doGet, doPost가 405 에러를 발생하도록 구현되어 있다.

왜 이렇게 설계했을까?

비즈니스 로직을 작성하기 위해 doGet, doPost 메소드를 무조건 재정의할 것이고, 만약 재정의하지 않는다면 doGet, doPost의 기본으로 405를 반환하도록 해서 오류를 알려주기 위함이라고 생각한다.

doGet을 구현하지 않았으니 -> get이 아니다!

이렇게 이해하면 간단하다.

profile
모르면 쓰지 말고 쓸 거면 알고 쓰자

0개의 댓글