본문 바로가기
Spring

[스프링 입문] 스프링 웹 개발 기초

by 스마일포테이토 2022. 12. 26.

스프링 웹 개발 기초

- 정적 컨텐츠 : 파일을 "그대로" 웹 브라우저에 내려주기

- mvc와 템플릿 엔진 : jsp, php와 같이 템플릿 엔진을 사용해 서버에서 html을 동적으로 바꿔 내리기

- api : json이라는 데이터 포맷으로 클라이언트에게 전송, 뷰나 리액트 사용할 때 데이터 내려주는 용, 서버끼리 (html 필요없을때)

 

 

정적 컨텐츠

스프링 부트는 정적 컨텐츠 기능을 자체제공

spring.io의 doc을 살펴보면

staic 폴더 아래에 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>

정적 컨텐츠로는 뭔가를 프로그래밍 할 수는 없고 그대로 보여줌

1. controller 쪽에서 hello-static이 있는지 찾아봄(controller가 우선순위)

2. 찾지 못했을 경우, resources안에 있는 static의 hello-static.html 찾아서 돌려줌

 

MVC와 템플릿 엔진

MVC: Model, View, Controller

 

JSP 사용하는 mvc1

 

view 는 화면을 그리는 데 집중

controller/ model과 관련된 부분은 비즈니스 로직과 관련된 부분에 집중

 

 

 

외부에서 parameter 받을때에는 @RequestParam

thymeleaf의 장점:  서버와 상관없이 html 확인 가능 ( hello! empty)

아래는 hello-template.html

<html xmlns:th="http://www.thymleaf.org">

<body>
<p th:text="'hello'+${name}">hello! empty</p>
</body>
</html>

 

HelloController

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

localhost/8080/hello-mvc로 접속하면

Whitelabel Error가 나는 이유는

WARN 32008 --- [nio-8080-exec-] .w.s.m.s.DefaultHandlerExceptionResolver :

Resolved [org.springframework.web.bind.MissingServletRequestParameterException:

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

requestparam에서  name이 없기 때문이다.

 

@RequestParam(value="name", required = true)

required가 false면 넘기지 않아도 되지만 기본이 true이기 때문에

localhost:8080/hello-mvc?name=spring!!!!

이런식으로 name에 값을 넘겨줘야 한다.

 

기존의

@RequestParam("name")

 에서 괄호 안에서 ctrl+p를 사용하면 뭐가 필요한지 확인할 수 있고, 여기에서 required의 기본값이 true임을 확인.

name=[  ]  [ ]로 전달받은 name이 hello-template.html에 들어가기 때문에

화면에 hello [] 형태로 렌더링 되는 것을 볼 수 있다.

정적일때는 html변환을 하지 않지만 mvc에서는 변환을 해서 넘겨준다.

소스보기를 했을 때, 변환이 되어있는걸 확인할 수 있다.

 

 

API

정적 콘텐츠를 제외하면 html로 내리냐 데이터로 바로 내리냐로 mvc패턴/api로 나뉜다.

 

 

HelloController

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

@ResponseBody

http에서의 header부와 body부, body부에 데이터를 직접 넣어주겠다는 annotation

view없이 그대로 요청한 서버에 내려감.

 

소스보기를 했을 때

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

 

 

 

문자가 아니라 데이터를 내놓기 위해

@GetMapping("hello-api")
@ResponseBody
public Hello helloApi(@RequestParam("name") String name){
    Hello hello= new Hello();
    hello.setNmae(name);
    return hello;
}

static class Hello{
    private String name; //private 접근하기 위해 getter/setter 사용

    public String getName(){
        return name;
    }
    
    public void setName(String name){
            this.name=name;
        }
}

return hello 로 문자가 아닌 객체를 넘긴다.

Json으로 넘어가는걸 확인할 수 있다.

@Responsebody 사용하여 객체 Json으로 반환하는것이 2022 기본

 

getter setter을 이용한 접근 방식을 프로퍼티 접근 방식이라고 한다.

 

 

 

 

*tip : 아래 상태에서 ctrl+shift+enter 하면 ); 자동완성

Hello hello = new Hello(

*tip : getter setter 만들 때 단축키 alt+insert

 

 

@Responsebody를 사용

- http의 body에 문자 내용을 직접 반환

- 기존의 viewResolver 대신에 HttpMessageConverter가 동작

-문자인지 객체인지에 따라서 두 가지 방법으로 처리

    -기본 문자 처리:StringHttpMessageConverter

    -기본 객체 처리: MappingJackson2HttpMessageConverter  ( 객체를 Json로 바꿔주는 라이브러리 Jackson, spring이 기 본 탑재하고있음 )

-byte 처리 등등 기타 여러 HttpMessageConverter가 기본으로 등록되어 있음

 

 

 

참고: 클라이언트의 HTTP Accecpt 헤더와 서버의 컨트롤러 반환 타입 정보 둘을 조합해서 HttpMessageConverter가 선택된다.   Accept헤더가 요청을 하는대로 보내줌(Json, Xml ...)