스프링 웹 개발 기초

KyungHoon Kim·2022년 9월 21일
0

스프링

목록 보기
2/6
post-thumbnail

1. 정적 컨텐츠

• 스프링부트 정적 컨텐츠 기능

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>

• 메인메소드를 실행한 후
src/main/java/hello.hellospring/HelloSpringApplication에서 Run
http://localhost:8080/hello-static.html url을 입력하면 아래처럼 정적 컨텐츠가 웹 브라우저에 출력된다.

출력 화면

정적 컨텐츠 출력 원리


2. MVC와 템플릿 엔진

• MVC: Model, View, Controller

Controller

main/java/hello.hellospring/controller(패키지)/HelloController(클래스)

@Controller
public class HelloController {
    @GetMapping("hello-mvc")
    public String helloMvc(@RequestParam("name") String name, Model model){
        //이전에는 attributeValue로 직접 값을 받았으나 
        //이번에는 파라미터를 외부에서 받는 것 
        model.addAttribute("name", name);
        return "hello-template";
    }
}

View

resources/templates/hello-template.html

<html xmlns:th="http://www.thymeleaf.org">
<body>
<p th:text="'hello ' + ${name}">hello! empty</p>
<!-- hello! empty는 없어도 그만이다. 실제 서버를 돌리면 ${name}이 뜬다 -->
</body>
</html>

실행
http://localhost:8080/hello-mvc?name=spring

출력 화면

MVC, 템플릿 엔진 동작 원리


3. API 방식 데이터 전달

@ResponseBody 문자 반환

main/java/hello.hellospring/controller(패키지)/HelloController(클래스)

@Controller
public class HelloController {
    @GetMapping("hello-string")
    @ResponseBody //http의 header와 body부 중 body부에 데이터를 직접 넣어주겠다는 것이다.
    public String helloString(@RequestParam("name") String name) {
        return "hello " + name;
        //spring을 주소창에 넣으면 "hello spring"이 그대로 나온다. 
        //이것은 문자를 내려받는 것 아래는 데이터를 내려받음
    }
}

HTTP의 BODY부에 문자 내용을 직접 반환한다.(HTML BODY TAG를 말하는 것이 아님)

실행
http://localhost:8080/hello-string?name=spring

@ResponseBody 문자 출력

@ResponseBody 객체 반환

main/java/hello.hellospring/controller(패키지)/HelloController(클래스)

@Controller
public class HelloController {
    @GetMapping("hello-api")
    @ResponseBody
    public Hello helloApi(@RequestParam("name") String name) {
        Hello hello = new Hello(); //객체 생성 => 객체처리는 json형태로 하게 된다.
        hello.setName(name); 
        //파라미터로 받은 name을 넣는다. 
        //json형태 key:value 중 value로 출력된다.
        return hello; //문자가 아닌 객체를 넘긴다.
    }
    
        static class Hello { 
        // static을 써서 HelloController클래스 안에 또 클래스 생성 => hello.~~~으로 쓸 수 있다.
        
        private String name; 
        // private은 외부에서 접근이 안되므로 getter setter로 접근한다
        
        public String getName() {
            return name;
        }
        
        public void setName(String name) {
            this.name = name;
        }
    }
    
    
}

@ResponseBody 를 사용하고, 객체를 반환하면 객체가 JSON으로 변환된다.

실행
http://localhost:8080/hello-api?name=spring

@ResponseBody 사용 원리

@ResponseBody 를 사용
• HTTP의 BODY부에 문자 내용을 직접 반환한다.
• viewResolver 대신에 HttpMessageConverter 가 동작한다.
• 기본 문자처리: StringHttpMessageConverter
• 기본 객체처리: MappingJackson2HttpMessageConverter
• byte 처리 등등 기타 여러 HttpMessageConverter가 기본으로 등록되어 있다.

profile
주니어개발자 시켜줘요

0개의 댓글