Spring - 스프링 웹 개발 기초

이동찬·2022년 4월 20일

Spring

목록 보기
4/20
post-thumbnail

스프링 웹 개발 기초

1. 정적 컨텐츠

서버에서 하는 것 없이 파일을 웹 브라우저에 내려주는 것
resource -> static -> hello-static.html
접근 방식 : localhost:8080/hello-static.html

2. MVC와 템플릿 엔진

정적 컨텐츠 : 파일을 단지 전달해 주는 것
MVC와 템플릿 엔진 : 서버에서 HTML을 변형하여 내려주는 방식

MVC : Model, View, Controller

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

이렇게 controller에 @Getmapping을 지정해주고 @Requestparam을 이용해 url링크에 대입한 값을 변수에 넘겨준다.

< hello-template.html >

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

</html>

이 상태로 run을 돌리고 hello-mvc에 들어가면 error가 뜬다.
그러한 이유는 url링크에 name값에 변수값을 지정해주지 않았기 때문이다.
그렇기에

localhost:8080/hello-mvc?name=1

이런식으로 입력을 해야한다.

짜자잔!!!!

3. API

json이라는 데이터 구조 포맷으로 클라이언트에게 데이터를 전달하는 것
서버끼리 통신할 때 많이 사용

잠와서 내일 듣고 정리.. goodnight!


어제 잠이 와서 못듣고 회사에서 인강으로 듣는당..!!

@GetMapping("hello-string")
@ResponseBody
public String helloString(@RequestParam("name") String name) {
return "hello " +name;
}

@ResponseBody의 의미
: html에 나오는 body를 뜻하는 것이 아닌 http에서 header와 body부분이 있다.
이 body부분에 데이터를 내가 직접 넣어주겠다라는 뜻이다.

그러면 요청한 클라이언트에 그대로 내려가게 된다.
template엔진과 차이가 뭐냐면 view 이런 것이 없다.
이 문자가 그대로 내려가게 된다. html구조가 아닌!!

만약 문자가 아닌 데이터를 돌라고 한다면? <- 이것 때문에 api를 많이 사용한다.

@GetMapping("hello-api")
@ResponseBody //json으로 반환하는 것이 기본이다.
public Hello helloApi(@RequestParam("name") String name) { //name이 value가 된다.
	Hello hello=new Hello();
    hello.setName(name); //파라미터로 넘어온 값을 넘긴다.
    return hello; //문자형이 아닌 객체형을 넘긴다.
}

static class Hello {
	private String name; //key
    
    public String getName() {
    	return name;
    }
    
    public void setName(String name){
    	this.name=name;
    }
    
}
  • static class로 만든다면 클래스안에서 Hello class를 또 쓸 수 있다.
    ex)HelloController.Hello처럼 쓸 수 있다.

  • alt+Insert 하면 getter and setter(window)

  • getter and setter 접근방식으로 property 접근 방식이라고도 부른다.

실행을 하게 되면

위의 사진이 json이라는 방식이다.
json은 key, value로 이루어진 구조이다.

정리
@ResponseBody를 사용

  • HTTP의 BODY에 문자 내용을 직접 반환
  • ViewResolver 대신에 HttpMessageConverter가 동작
  • 기본 문자처리 : StringHttpMessageConverter
  • 기본 객체처리 : MappingJackson2HttpMessageConverter
  • byte 처리 등등 기타 여러 HttpMessageConverter가 기본으로 등록되어 있음

*Jackson이란?
-> 객체를 json으로 바꿔주는 라이브러리중 하나이다.

0개의 댓글