ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 스프링 ㅡMVC (Response, Request)
    스프링 2023. 4. 15. 17:15

    MVC  :  Model, view , Controller 의 디자인 패턴

     

    정적 웹페이지(static)

    동적 웹페이지(dynamic)

     

    클라이언트 --> Server   은 Request

    클라이언트 <-- Server   은 Response

     

    Model   :  url혹은 html안에 정보들

    View     :  html, Jsp, Thymelaf

    Controller   :  왔다갔다 서빙하는 애

     

    정적인 웹페이지를 주는 경우

    클라이언트 쪽에서 요청이 들어오면 Controlle는 Model로 받아서 처리를 한 후, 클라이언트에게 view을 반환

    클라이언트에게 정적인 웹페이지를 내려줌

     

    동적인 웹페이지를 주는 경우

    클라이언트에서 요청이 오면 Controller는 이걸 Model로 받아서 처리 한 후, Templats엔진 에게 View, Model을 전달

    Templats엔진은 이걸 Model을 잘 처리해서 View와 합쳐 클라이언트에게 동적인 웹페이지를 내려줌

     

    Templats엔진(템플릿 엔진)  -  Thymeleaf (주로쓰임)


    Response

    @Controller : 이 클래스를 Controller로 사용한다고 지정

    @RequestMapping("/url") : 초기 url 모든 url은 이 url을 통해 들어갈 수 있음.

    @GetMapping  :  해당 url로 들어가면 요청 , return을 반환

    @Response Body  :  클라이언트에게 View를 주는 것이 아니라 return을 그냥 Body에 찍어서 클라이언트에게 넘김

    @RestController  :  @Controller와@Response Body가 합쳐진 에노테이션

     

    서버는 

    1. 정적웹페이지   (View)

    2. 동적웹페이지  (View + Model)

    3. Json 형식을 Body에

    4.html형식을 body에 (이것도 Json) 

    을 반환

     

    @Controller
    @RequestMapping("/response")
    public class HelloResponseController {

    private static long visitCount = 0;

    @GetMapping("/html/redirect")
    public String htmlFile() {
    return "redirect:/hello.html";
    }

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

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

    @GetMapping("/html/dynamic")
    public String helloHtmlFile(Model model) {
    visitCount++;
    model.addAttribute("visits", visitCount);
    return "hello-visit";
    }

    @ResponseBody
    @GetMapping("/json/string")
    public String helloStringJson() {
    return "{\"name\":\"르세라핌\",\"age\":20}";
    }

    @ResponseBody
    @GetMapping("/json/class")
    public Star helloJson() {
    return new Star("르세라핌", 20);
    }
    }

    Request

     

    메소드 안에 들어간 에노테이선들이 중요함!!

    어떤 에노테이션들을 쓰는지에 따라 값을 가져오는 방식이 달라짐

    1. @PathVariable  :  url에서 {name}로 데이터를 가져오기

    2. @RequestParm  :  url에서 param?name=      &age=    로 데이터를 가져옴  (쿼리 방식)  //Get방식

    3. @RequestParm : post방식으로 데이터를 가져옴 Get방식과 비슷하게 보여서 햇갈릴 수 있음.

    4. @ModelAttribute : 객체 형식으로 데이터를 받음 (name과 age를 따로 받는게 아니라 같이 받음)

    Star클래스로 변환해서 받음.(데이터를 받는 클래스에 @Satter 넣어줘야함)

    5. @RequestBody  :  요청 바디(body)에 있는 데이터를 JSON 형식으로 가져옴(이것도 객체로 받아옴)

     

    @ModelAttribute와@RequestBody은 값을 받아오는 클래스의 값과 받은 값이 일치해야됨

     

    따라서, @ModelAttribute는 요청 파라미터를 바인딩할 때 사용하고, @RequestBody는 요청 바디를 바인딩할 때 사용합니다. 이 두 어노테이션은 다른 용도를 가지고 있으며, 각각의 적절한 상황에서 사용되어야 합니다.

     

    바인딩 : 바인딩(Binding)은 컴퓨터 프로그래밍에서 변수와 데이터를 서로 연결하는 작업을 말합니다. 이는 프로그램에서 변수를 선언하고 값을 할당할 때 발생하는 과정입니다.

     

     

    1. @PathVariable 

    @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);
    }

    url로 데이터를 넘겨줘서 메소드에 담아 그대로 같은 url로 뿌림, @ResponseBody니까 바디에 붙여서 Json형식으로 뿌림

     

     

     

    2. @RequestParm      (Get방식)

    @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);
    }

     

     

     

    3. @RequestParm       (Post방식)

    @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);
    }

     

     

     

    4. @ModelAttribute        (Post방식)(어노테이션 생략가능)

    @PostMapping("/form/model")
    @ResponseBody
    public String helloRequestBodyForm(@ModelAttribute Star star) {
    return String.format("Hello, @RequestBody.<br> (name = %s, age = %d) ", star.name, star.age);
    }

     

     

     

     

    5. @RequestBody           (Post방식)

    @PostMapping("/form/json")
    @ResponseBody
    public String helloPostRequestJson(@RequestBody Star star) {
    return String.format("Hello, @RequestBody.<br> (name = %s, age = %d) ", star.name, star.age);
    }

     

     

     

     

     

     

     

    '스프링' 카테고리의 다른 글

    스프링부트 (타임스탬프,오전 1시 마다 가격 업데이트)  (0) 2023.04.20
    스프링 부트 (메모장만들기) *  (0) 2023.04.17
    IoC 와 DI 용어 이해하기  (0) 2023.04.15
    JPA (Java와 DB 연동)  (0) 2023.04.15
    SQL (Query문)  (0) 2023.04.14
Designed by Tistory.