스프링 웹 개발 기초

김세호·2023년 1월 6일
0

Spring Boot

목록 보기
6/6

웹 개발

웹 개발에는 크게 3가지 종류가 있다.

  • 정적 컨텐츠 : 파일을 그대로 웹브라우저에 저장하고 요청 시 client에게 반환
  • MVC와 템플릿 엔진 :jsp,php 등 템플릿 엔진으로 서버에서 html을 동적으로 바꿔서 client에게 반환
  • API : JSON 데이터 포멧으로 client에게 반환
    API 란?? https://brunch.co.kr/@ogaa2143/30

정적 컨텐츠

스프링 부트는 정적 컨텐츠 기능을 제공함
https://docs.spring.io/spring-boot/docs/2.3.1.RELEASE/reference/html/spring-boot-features.html#boot-features-spring-mvc-static-content
src/resources/static 폴더에 hello-static.html 파일을 생성


아래와 같이 코드 작성 후 실행

<!DOCTYPE HTML>
<html>
<head>
 <title>static content</title>
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
정적 컨텐츠 입니다.
</body>
</html>




  • 내장 톰켓 서버가 요청을 받고 스프링 컨테이너에서 관련 컨트롤러(hello-static)가 있는지 찾아본다.
  • 컨트롤러가 없을 경우, 그 다음 스프링부트는 resources에 있는 hello-static.html을 찾고 있으면 반환한다.

MVC와 템플릿 엔진

MVC : Model, View, Controller

@GetMapping("hello-mvc")
    public String helloMvc(@RequestParam("name") String name, Model model){
        model.addAttribute("name", name); // 파라미터로 넘어온 name을 넘겨주겠다.
        return "hello-template";
    }

파라미터로 넘어온 name을 받고 이를 다시 hello-template로 보내준다.

template에 hello-template.html을 만들어준다.


<html xmlns:th="http://www.thymeleaf.org">
<body>
<p th:text="'hello ' + ${name}">hello! empty</p>
<!--템플릿 엔진으로 동작하면 p 태그 안의 hello! empty가 text 내용으로 치환-->
</body>



실행 후 http://localhost:8080/hello-mvc.html 로 접속 해보면 에러가 난다.
인텔리제이 에서 에러를 확인하면

Required request parameter 'name' for method parameter type String is not present

name 값을 넣어줘야 한다


get방식으로 name에 spring! 파라미터값을 넣어주니 잘 동작 한다.



내장 톰켓 서버를 거쳐 스프링 컨테이너에서 컨트롤러의 매핑된 메소드를 찾아 호출한다.
뷰 리졸버로 값을 받아 템플릿 엔진으로 넘겨 렌더링을 하여 변환한 html을 반환한다.

API

0개의 댓글