반응형
Notice
Recent Posts
Recent Comments
Link
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
Archives
Today
Total
관리 메뉴

웹풀스택 공부 중

16 - 2. Spring - Controller와 RequestMapping 를 이용한 정적 동적 페이지 반환 본문

웹개발/Spring

16 - 2. Spring - Controller와 RequestMapping 를 이용한 정적 동적 페이지 반환

lukeit 2024. 11. 14. 09:12

정적 및 동적 페이지 반환

  • 정적 페이지를 반환

    • ErrorController를 통해 정적 에러 페이지를 처리할 수 있다

      • 특정 상태 코드 (404, 400, 500, …)에 따라 정적 HTML파일이 반환 가능하다

      • BasicErrorController라는 Spring 기본 구현체를 통해, 사용자 정의 Controller없이도 정적 에러페이지를 처리할 수 있다

        • 예시

             @Controller
            public class CustomErrorController implements ErrorController {
          
                @RequestMapping("/error")
                public String handleError(HttpServletRequest request) {
                    return "error"; // 정적 HTML 에러 페이지 반환
                }
            }
        • 에러별 분기점 나눠서 진행하기:

            @Controller
            public class CustomErrorController implements ErrorController {
                @RequestMapping(value = "/error", method = RequestMethod.GET)
                public String handleError(HttpServletRequest request) {
                    Object status = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
                    if (status != null) {
                        Integer statusCode = Integer.valueOf(status.toString());
                        if (statusCode == HttpStatus.NOT_FOUND.value()) {
                            return "error/404";
                        } else if (statusCode == HttpStatus.INTERNAL_SERVER_ERROR.value()) {
                            return "error/500";
                        }
                    }
                    return "error";
                }
            }
    • 이것들은 Thymeleaft를 통해 구현되며

      • Controller 없이 View를 반환하기 위해서는

        • /resources/templates/ 의 디랙토리 안에 html파일을 위치시키고, return 을 통해 그 파일을 반환시키면 된다
          • return 'index.html' 을 한다면 정적 웹페이지로 이동한다
      • Error 코드에 따라 세부 커스터마이징을 하고자 한다면

        • /resources/templates/error 라는 디렉토리를 추가하여 커스터마이징을 진행하면 된다

        • 예시)

          
            // 이런식으로 먼저 어떤 값을 넘길지, 어디로 넘길지 (RequestMapping) 설정후,
          
            @Controller
            public class CustomErrorController implements ErrorController {
          
                @RequestMapping("/error")
                public ModelAndView handleError(HttpServletRequest request) {
                    ModelAndView modelAndView = new ModelAndView();
                    Object status = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
                    if (status != null) {
                        Integer statusCode = Integer.valueOf(status.toString());
                        if (statusCode == HttpStatus.NOT_FOUND.value()) {
                            modelAndView.addObject("status", statusCode);
                            modelAndView.addObject("reason", HttpStatus.NOT_FOUND.getReasonPhrase());
                        } else if (statusCode == HttpStatus.INTERNAL_SERVER_ERROR.value()) {
                            modelAndView.addObject("status", statusCode);
                            modelAndView.addObject("reason", HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase());
                        }
                    }
                    modelAndView.setViewName("error");
                    return modelAndView;
                }
            }
          
            // resources/templates/error.html, 이런식으로 받아올 수 있다
          
            <!DOCTYPE html>
            <html xmlns:th="http://www.thymeleaf.org">
            <head>
                <meta charset="UTF-8" />
                <title>Custom Error Page</title>
            </head>
            <body>
            <h1>Custom Error Page</h1>
            <div>- status: <span th:text="${status}"></span></div>
            <div>- reason: <span th:text="${reason}"></span></div>
            </body>
            </html>
          
          • 위 예시의 경우 return [ModelAndView] 를 반환하였다
            • th... 가 붙은 코드는 Thymeleaft 문법이다
            • ModelAndView란 Model + ViewTemplate + viewName을 보내주어
            • 상황별 동적 페이지*를 반환할 수 있게 해준다
              • Model은 기본적으로 Map (JSON) 구조이다
                • Key, value pair
            • 사용방법:
              1. ModelAndView 생성
                1. ModelAndView modelAndView = new ModelAndView();
              2. ViewTemplate 이름설정
                1. modelAndView.setViewName("error");
              3. Model 데이터 설정
                1. modelAndView.addObject("status", statuscode")
              4. 다 만든 ModelAndView 객체 반환
                1. return modelAndView

@Controller

WAS에서 어떤 요청을 받았을때, 웹 페이지를 반환할것인가?

  • 어떤 REST API (Method + URL)요청을 받았을때 어떻게 처리할지 정의한다
@Controller
public class IndexController {

    **@RequestMapping(method = RequestMethod.GET, value = "/")**
    public String index() {
        **return "index";**
    }
}
  • ex.) return index : resoruces/templates + ‘index’ + .html 이라는 뜻이다
    • @Controller에서 String으로 ViewTemplate 반환 시 Thymeleaf로 접두사, 접미사가 자동으로 적용된다!
      • 이것으로 반환하는 String 값은 모드 ViewTemplate을 의미한다

@RequestMapping

@RequestMapping(**value** = "/", **method** = RequestMethod.GET)
  • @Controller 내 @RequestMapping은 웹 클라이언트가 보내는 어떤 요청을 받아서 어떤 메서드로 처리할지 정의한다

    1. value = 요청한 URL 중 Origin 을 제외한 Path 부분
      1. ex.) value = “/” = http://localhost:8080 + ‘/’
    2. method = HTTP 요청 메서드 (GET, POST, DELETE, …)
      1. ex.) method = RequestMethod.GET = GET Method를 사용한다는 의미
  • 메서드 단위의 @RequestMapping을 통헤 2개의 메서드 각각 URL 상세 정의해보는 예시

      @Controller
      public class UserController {
    
          @RequestMapping(method = RequestMethod.GET, value = **"/users"**)
          public String userPage() { ... }
    
          @RequestMapping(method = RequestMethod.GET, value = **"/users/1/detail"**)
          public String detailPage() { ... }
  • 클래스 단위의 @RequestMapping = 해당 URL에 대한 다수 (메서드)의 요청 처리

반응형

'웹개발 > Spring' 카테고리의 다른 글

16 - 3. Spring - Spring MVC  (0) 2024.11.14
16 - 1. Spring의 기초  (1) 2024.11.14