공부 흔적남기기

Spring MVC 예제를 통한 이해 본문

web study/Spring

Spring MVC 예제를 통한 이해

65살까지 코딩 2022. 1. 22. 23:13
728x90
반응형

코드를 먼저 천천히 살펴보며 이해해보자

package com.sparta.springmvc;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

@Controller
@RequestMapping("/hello/request")
public class HelloRequestController {
    @GetMapping("/form/html")
    public String helloForm() {
        return "hello-request-form";
    }

    // [Request sample]
// GET http://localhost:8080/hello/request/star/BTS/age/28
    @GetMapping("/star/{name}/age/{age}")
    @ResponseBody
    public String helloRequestPath(@PathVariable String name, @PathVariable int age)
    {
        return String.format("Hello, @PathVariable.<br> name = %s, age = %d", name, age);
    }

    // [Request sample]
// GET http://localhost:8080/hello/request/form/param?name=BTS&age=28
    @GetMapping("/form/param")
    @ResponseBody
    public String helloGetRequestParam(@RequestParam String name, @RequestParam int age) {
        return String.format("Hello, @RequestParam.<br> name = %s, age = %d", name, age);
    }

    // [Request sample]
// POST http://localhost:8080/hello/request/form/param
// Header
// Content type: application/x-www-form-urlencoded
// Body
// name=BTS&age=28
    @PostMapping("/form/param")
    @ResponseBody
    public String helloPostRequestParam(@RequestParam String name, @RequestParam int age) {
        return String.format("Hello, @RequestParam.<br> name = %s, age = %d", name, age);
    }

    // [Request sample]
// POST http://localhost:8080/hello/request/form/model
// Header
// Content type: application/x-www-form-urlencoded
// Body
// name=BTS&age=28
    @PostMapping("/form/model")
    @ResponseBody
    public String helloRequestBodyForm(@ModelAttribute Star star) {
        return String.format("Hello, @RequestBody.<br> (name = %s, age = %d) ", star.name, star.age);
    }

    // [Request sample]
// POST http://localhost:8080/hello/request/form/json
// Header
// Content type: application/json
// Body
// {"name":"BTS","age":"28"}
    @PostMapping("/form/json")
    @ResponseBody
    public String helloPostRequestJson(@RequestBody Star star) {
        return String.format("Hello, @RequestBody.<br> (name = %s, age = %d) ", star.name, star.age);
    }
}

먼저 Mapping 위에 @ResponseBody가 들어간 경우 Response 데이터를 return한다. 

그렇지 않고 그냥 return "값" 이 있으면 먼저 타임리프가 templates에 값과 같은 html파일이 있는지 확인하고 있으면 html 값을 리턴한다. 못 찾으면 에러페이지가 나온다.

이제 @ResponseBody가 붙은 코드들을 하나씩 나열해 비교해보면

먼저 @PathVariable은 URI에 담긴 값을 가져와 사용하는 것이다.

@RequestParam은 query로 날라오는 key&value 형태에서 key값을 조회에 value값을 가져와 사용하는 것이다. 

이떄 GET방식은 URI에 query가 나타나지만 POST방식은 나타나지 않는다.

@ModelAttribute 방식은 객체를 매개변수로 받아 객체의 값에 배정해주시는 식으로 한다.

@RequestBody는 객체를 통해 값을 받는다.

@ModelAttribute와 @RequestBody는 객체에 값을 넣어준다는 공통점이 있다. 하지만 ModelAttribute는 파라미터 값을 DTO에 넣어준다는 특징이 있고 RequestBody는 json과 같은 값을 받는다는 차이점이 있다!

 

 

package com.sparta.springmvc;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

@Controller
@RequestMapping("/hello/response")
public class HelloResponseController {
    // [Response header]
// Location: http://localhost:8080/hello.html
    @GetMapping("/html/redirect")
    public String htmlFile() {
        return "redirect:/hello.html";
    }

    // [Response header]
// Content-Type: text/html
// [Response body]
// * resources/templates/hello.html 의 text 내용
// <!DOCTYPE html>
// <html>
// <head><meta charset="UTF-8"><title>By Templates engine</title></head>
// <body>Hello, Spring 정적 웹 페이지!!</body>
// </html>
    @GetMapping("/html/templates")
    public String htmlTemplates() {
        return "hello";
    }

    // [Response header]
// Content-Type: text/html
// [Response body]
// <!DOCTYPE html>
// <html>
// <head><meta charset="UTF-8"><title>By @ResponseBody</title></head>
// <body>Hello, Spring 정적 웹 페이지!!</body>
// </html>
    @GetMapping("/body/html")
    @ResponseBody
    public String helloStringHTML() {
        return "<!DOCTYPE html>" +
                "<html>" +
                "<head><meta charset=\"UTF-8\"><title>By @ResponseBody</title></head>" +
                "<body> Hello, 정적 웹 페이지!!</body>" +
                "</html>";
    }

    // [Response header]
// Content-Type: text/html
// [Response body]
// * resources/templates/hello-visit.html 의 text 내용
    @GetMapping("/html/dynamic")
    public String helloHtmlFile(Model model) {
        visitCount++;
        model.addAttribute("visits", visitCount);
// resources/templates/hello-visit.html
        return "hello-visit";
    }

    private static long visitCount = 0;

    // [Response header]
// Content-Type: text/html
// [Response body]
// {"name":"BTS","age":28}
    @GetMapping("/json/string")
    @ResponseBody
    public String helloStringJson() {
        return "{\"name\":\"BTS\",\"age\":28}";
    }

    // [Response header]
// Content-Type: application/json
// [Response body]
// {"name":"BTS","age":28}
    @GetMapping("/json/class")
    @ResponseBody
    public Star helloJson() {
        return new Star("BTS", 28);
    }
}

model에 addAttribute를 통해 값을 넣으면 자동으로 타임리프가 넣은 값을 조회에 html에 적용한다.

Json형식으로 Response가 하고 싶다면 객체를 넣어서 보내야 한다.!

@Responsebody + @Controller -> @RestController!

 

이것들을 정리한 표 스파르타코딩클럽 Spring심화반에서 튜터님이 만들어주신 것이다.

 

출처:https://spartacodingclub.kr/online/spring_plus

 

스파르타코딩클럽 [Spring 심화반]

Spring 뽀개고 취업하기

spartacodingclub.kr:443

 

728x90
반응형