티스토리 뷰

스프링부트를 막 입문하기 시작한 스린이! 배우면서 정리하는 목적으로 포스팅을 하는 것이기 때문에

틀린 내용이 있다면 댓글로 남겨주세요! O(∩_∩)O

 

  • 정적 컨텐츠 : 서버에서 어떠한 작업이 필요없이 그냥 파일을 넘겨주기

  • MVC와 템플릿 엔진 : jsp, php와 같은 템플릿엔진. 서버에서 프로그래밍을 해서 html을 동적으로 넘겨주기

  • API : vue, react, 서버끼리 통신할 때 등등

1. MVC와 템플릿 엔진

_Controller

@Controller
public class TestController {

	@GetMapping("test")
    public String testMvc(@RequestParam("name") String name, Model model) {
    	model.addAttribute("name", name);
        return "test-template";
    }
}

_View 

<html xmlns:th="http://www.thymeleaf.org">
<body>
<p th:text="'hello '+${name}"> hello ! </p>
</body>
<html>

Controller에서 parameter로 받았던 name이 thymeleaf 문법을 사용하여 ${name}에 적용된다.

따라서 localhost:8080/test?name=young 을 접속하면 hello young 이라는 페이지가 보일 것!

 

2. API

_Controller

@Controller
public class TestController {

	@GetMapping("test")
    @ResponseBody
    public String testString(@RequestParam("name") String name, Model model) {
        return "hello "+name;
    }
}

달라진점은 @GetMapping아래 @ResponseBody가 추가되었다는 점이다.

@ResponseBody는 view없이 문자열이 그대로 전달되는데 http통신의 body 부분에 직접 해당 데이터를 넣겠다는 의미이다.

따라서 localhost:8080/test?name=young 을 접속하면 "hello young" 문자열이 보일 것!

 

이 때, 반환값이 String이 아니고 객체일 수도 있는데 그때는 기본으로 json형태로 반환된다. (JsonConverter)

  • 기본 문자처리 : StringHttpMessageConverter
  • 기본 객체처리 : MappingJackson2HttpMessageConverter
    • Jackson : 객체를 json으로 바꿔주는 라이브러리

 

참고로 @ResponseBody를 사용할 경우, class위에 @Controller annotation을 @RestController로 바꿀 수 있다.

@RestController = @Controller + @ResponseBody

 

3. Controller 작성방법

  1. HTTP Method : GET, POST, PUT, DELETE etc ...

  2. URL Path : /hello, /hi, /login, /sign-up etc...

  3. Do Something

@GetMapping("/hello")
public String hello() { return "hello"; }

→ get 으로 들어온 /hello 대해서 요청이 들어오면 hello()함수 실행되고 "hello"반환됨

 

 

참고) 인프런 - 스프링 웹 개발 기초 강좌

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
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
글 보관함