웹 개발 방법

ny0011·2022년 10월 6일

스프링 입문

목록 보기
3/4

웹 개발 방법
1. 정적 컨텐츠
2. MVC와 템플릿 엔진
3. API

  • 앱에 데이터 전달할 때 json 형식으로 API 전달
  • 서버 간 통신할 때 사용

1. 정적 컨텐츠

spring boot에서 정적 컨텐츠 기능을 제공함

  • resources:static 밑에 어떤 html 파일을 만들어서 저장
  • localhost:8080/파일이름.html 을 실행하면 파일을 보여줌

2. MVC와 템플릿 엔진

MVC: Model, View, Controller

Controller

@GetMapping("hello-mvc")
public String helloMvc(@RequestParam("name") String name, Model model){
        model.addAttribute("name", name);
        return "hello-mvc-temp";
    }

View

<html xmlns:th="http://www.thymeleaf.org">
<body>
<p th:text="'hello ' + ${name}">hello! empty</p>
</body>
</html>
  • thymeleaf가 name에 값을 넣어서 html 변환해서 보여줌

3. API

  • @ResponseBody를 사용하면 뷰 리졸버(viewResolver)를 사용하지 않고 HttpMessageConverter를 사용함
    • 기본 문자처리: StringHttpMessageConverter
    • 기본 객체처리: MappingJackson2HttpMessageConverter

@ResponseBody 문자 반환

  • 문자 그대로를 보여줌
@GetMapping("hello-string")
@ResponseBody
public String helloString(@RequestParam("name") String name){
        return "hello"+name;
    }

@ResponseBody 객체 반환

  • @ResponseBody 를 사용하고 객체를 반환하면 spring(MappingJackson2HttpMessageConverter)이 객체를 json 형식으로 변경해서 리턴함
@GetMapping("hello-api")
@ResponseBody
public Hello helloApi(@RequestParam("name") String name){
        Hello hello = new Hello();
        hello.setName(name);
        return hello;
    }

0개의 댓글