설명 PathPattern 공식 문서 ? : 한 문자 일치 /pages/t?st.html YES: /pages/test.html , /pages/tXst.html NO : /pages/toast.html * : 경로( / ) 안의 모든 문자 일치 /resources/*.png YES: /resources/photo.png NO : /resources/favority.ico ** : 하위 경로 모든 문자 일치 /resources/** /resources/image.png , /resources/css/spring.css {spring} : spring 이라는 변수로 캡처 /resources/{path} /resources/robot.txt -> path 변수에 "robot.txt" 할당 @PathVariable("path") 로 접근 가능 {*spring} : 하위 경로 끝까지 spring 변수에 캡쳐 /items/{*path} /items/1/add -> path 변수에 "/1/add" 할당 {spring:[a-z]+} : 정규식 이용 /items/{path:[a-z]+} YES: /items/robots NO : /items/123 예제 1 - {*spring} @GetMapping("/hello/{*name}") @ResponseBody public String handleTest( @PathVariable String name ) { log.info("name = {}", name); return name; } GET http://localhost:8080/hello/path-test -> name = /path-test === GET http://localhost:8080/hello/path-test/other -> name = /path-test/other 예제 2 - 정규식 @GetMapping("/static/{name:[a-z-]+}-{version:\\d\\.\\d\\.\\d}{ext:\\.[a-z]+}") @ResponseBody public String handle( @PathVariable String name, @PathVariable String version, @PathVariable String ext ) { log.info("name = {}", name); log.info("version = {}", version); log.info("ext = {}", ext); return "/" + name + "/" + version + "/" + ext; } GET http://localhost:8080/pathtest-1.0.0.jar -> name = pathtest version = 1.0.0 ext = .jar 잘못된 사용 @GetMapping("/static/{*fullpath}{name}") @ResponseBody public String runtimeError( @PathVariable String fullpath, @PathVariable String name ) { log.info("fullpath = {}", fullpath); log.info("name = {}", name); return name; } Description: Invalid mapping pattern detected: /static/{*fullpath}{name} ^ No more pattern data allowed after {*...} or ** pattern element {*...} 또는 ** 패턴 요소 다음에는 다른 패턴 데이터 를 사용할 수 없습니다.
개발하다보면 실무에서도 아키텍쳐를 변경해야할 때가 있다. 이 때, 구조를 수정할 때는 구조만 건들여야 한다. 수정하다보면 구조말고도 디테일한 부분이 눈에 밟혀 수정하고 싶은 충동이 생기는데, 그때 한 번에 개선을 하게 되면 다른 사람이 처리하는데도 힘들고, 사람이 다 기억하기도 힘들다. 그러니, 디테일한 것이 보여도 TODO 리스트에 적은 다음 넘어가고, 큰 구조를 먼저 변경이 완료된 후, 테스트까지 완료되면 커밋하고 나서 디테일한 것을 변경하자. 말씀을 듣자마자 과거에 경험했던 일들이 주마등처럼 스쳐 지나갔습니다... ㅋㅋㅋㅋ... 이 문구를 따로 저장해서 마음 속 깊이 새기도록 하겠습니다.
강의 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); } }
별건 아니지만 5분간 삽질한 내용 공유 드립니다. 19:25 부분에서 강사님이 말씀하신것처럼 필드 유지가 안되는 경우 @Getter @Setter public class MemberForm { @NotEmpty(message = "값이 존재해야 합니다.") private String name; private String city; private String street; private String zipcode; } MemberForm 모델에 수정자가 존재하는지 확인해보세요. @Setter를 사용하지 않는 습관때문에 간단한 것도 놓치네요. 혹시 저와 같은 문제를 겪으신 분을 위해 공유합니다.
안녕하세요 현재 영한님 스프링 강의를 듣고 있습니다. 우선 좋은강의만들어주셔서 감사합니다. 제가 지금 야생형으로 해서 JPA 활용1편을 거의 다들었고 JPA기본편을 들을 차례인데요, 개발바닥 이벤트로 영한님의 모든 강의를 구매해놓은 상태입니다. 그래서 문득 JPA강의를들으면서 MVC강의도 같이 들으면 좀더 이해가 잘 될까? 아니면 기존 야생형코스를 다듣고 MVC를 추가로 듣는게 나을까? 고민이 되더라구요 JPA활용1편을 무작정 들어보면서 흥미가 더 올랐고 모르는부분은 제가 찾아가면서 해보니 가면갈수록 내공이쌓여서?? 이해가 잘 되고 있습니다.ㅎㅎ 1월중순부터 지인들이랑 프로젝트를 하나 해보기로한 상황이기도하고.. 궁금해서 여쭤봅니다!