inflearn logo
강의

강의

N
챌린지

챌린지

멘토링

멘토링

N
클립

클립

로드맵

로드맵

지식공유

스프링 MVC 1편 - 백엔드 웹 개발 핵심 기술

Hello 서블릿

웹 브라우저에서 hello world가 안보이던 이유

362

김회민
0

강의 9분에서 진행되던 파라미터를 Response에 다시 돌려주던 부분에서 저는 왜 에러 페이지가 뜰까 고민하다가 발견한 것을 정리했습니다.

강의 처음부터 service 메소드를 오버라이딩할 때 super.service(req, resp);가 없었지만 Ctrl + Shift + A를 통해 자동으로 생성할때에는 저 한 줄이 자동으로 붙습니다. 이를 제거해주지 않으면 에러페이지가 표시되고, 응답은 405로 표시됩니다.

저 코드의 의미는 부모 클래스의 service 메소드를 실행하라라는 의미인데, 들어가보면 아래의 코드를 만날 수 있습니다.

if (method.equals(METHOD_GET)) {
    long lastModified = getLastModified(req);
    if (lastModified == -1) {
        // servlet doesn't support if-modified-since, no reason
        // to go through further expensive logic
        doGet(req, resp);
    } else {
        long ifModifiedSince;
        try {
            ifModifiedSince = req.getDateHeader(HEADER_IFMODSINCE);
        } catch (IllegalArgumentException iae) {
            // Invalid date header - proceed as if none was set
            ifModifiedSince = -1;
        }
        if (ifModifiedSince < (lastModified / 1000 * 1000)) {
            // If the servlet mod time is later, call doGet()
            // Round down to the nearest second for a proper compare
            // A ifModifiedSince of -1 will always be less
            maybeSetLastModified(resp, lastModified);
            doGet(req, resp);
        } else {
            resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        }
    }
}

나름 해석해보면 GET 요청이 올 때, doGet 메소드로 보내는 것을 확인할 수 있고, doGet 메소드는 아래와 같습니다.

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

코드를 보면 상속을 하지않은 원형 doGet 메소드는 405코드로 바로 응답하도록 작성되어 있는 것을 확인할 수 있습니다.

이를 해결하는 방법은 2가지가 있습니다.

@WebServlet(name = "helloServlet", urlPatterns = "/hello")
public class HelloServlet extends HttpServlet {
    @Override
    protected void service(
            HttpServletRequest req, HttpServletResponse resp
    ) throws ServletException, IOException {
        super.service(req, resp);
        System.out.println("HelloServlet.service");
        System.out.println("req = " + req);
        System.out.println("resp = " + resp);
    }

    @Override
    protected void doGet(
            HttpServletRequest req, HttpServletResponse resp
    ) throws IOException {
        // 파라미터 획득
        String userName = req.getParameter("username");
        System.out.println("userName = " + userName);

        // Response Header 설정
        resp.setContentType("text/html");
        resp.setCharacterEncoding("utf-8");

        // Response
        resp.getWriter().write("hello " + userName);
    }
}

spring mvc

답변 1

0

김영한

김회민님 좋은 내용 공유 감사합니다^^

MVC 패턴을 정확히 익힐려면 어떻게 해야할까요?

0

372

1

선생님 조언 부탁드립니다.

0

301

0

WebFlux를 실무에 적용하기 전에 고민이 있습니다.

0

322

0

커리큘럼 고민

0

377

1

스프링 백엔드 개발 로드맵

0

468

1

Spring 공부 어떤 강의 순서로 듣는게 좋은가요?

0

722

1

프로젝트와 강의 우선 순위 관련 질문드립니다!

1

476

1

코틀린 개발자로 취업하게 되면서 고민이 생겼습니다.

0

415

1

강의 구입에 관한 질문입니다(설연휴 할인 관련)

0

394

1

학습 방향에 고민이 있습니다.

0

509

1

관리자권한으로 실행 자체가 뜨지 않으면 어떻게 해야할까요?

0

405

1

스프링 선수학습이 필요한가요?

1

517

1