웹 브라우저에서 hello world가 안보이던 이유
스프링 MVC 1편 - 백엔드 웹 개발 핵심 기술
강의 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가지가 있습니다. 상속받은 HelloServlet의 service 메소드에서 super.service(req, resp) 를 제거하는 것. 상속받은 HelloServlet에 doGet 메소드를 추가로 오버라이딩해서 그곳에 Response를 조작하는 코드를 작성하는 것이 있습니다. 이에 해당하는 방법의 코드는 아래와 같습니다. @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





