TIL|「Spring」コントローラ応答


個人の宿題をするたびに混同されるので、簡単に整理したいです.整理用の文章なので、ほとんどの説明は省略しますので、参考にしてください.
リファレンス
  • HTTPメッセージ
  • 静的Webページ


    1.静的フォルダ


    src-main-resources-staticでhome.htmlファイルを作成し、localhost:8080/home.htmlに入るとコントローラを経由せずにspringでファイルを見つけて画面に表示します.

    2. Redirect


    HomeController
    @Controller
    public class HomeController {
    
        @GetMapping("/html/redirect")
        public String staticHtmlFile() {
            return "redirect:/home.html";
        }
    }
    http://localhost:8080 /html/redirect - request
    http://localhost:8080 /home.html - response(redirect:/home.html)

    3.ビューテンプレート(Thyemleafベース)


    src - main - resources - templates - hello.htmlファイルの生成
    HomeController
    @Controller
    public class HomeController {
    
        @GetMapping("html/templates")
        public String htmlTemplates() {
            return "hello";
        }
    }
    http://localhost:8080 /html/templates - request
    ThyemleafはString"hello"をView nameと認識する
    →resources/templatesで「hello.html」を見つけ、画面に表示する

    4. @ResponseBody


    HomeController
    @GetMapping("/body/html")
    @ResponseBody
    public String helloStringHTML() {
        return "<!DOCTYPE html>" +
               "<html>" +
                   "<head><title>By @ResponseBody</title></head>" +
                   "<body> Hello, 정적 웹 페이지!!</body>" +
               "</html>";
    }
    戻ってきたStringコンテンツは、Viewを介して画面に表示されません.
    (3、内容が同じかビューを通らないかで大きな違いがあります.)
    http://localhost:8080 /body/html - request

    ダイナミックWebページ


    src - main - resources - templates - hello-visit.htmlファイルの生成
    hello-visit.html
    ページをリフレッシュするたびに、アクセス者セクションが動的に変化します.
    <!DOCTYPE html>
    <html>
    <head><meta charset="UTF-8"><title>Hello Spring</title></head>
    <body>
        <div>
            Hello, Spring 동적 웹 페이지입니다!
        </div>
        <div>
            (방문자 수: <span th:text="${visits}"></span>)
        </div>
    </body>
    </html>
    HomeController
    @Controller
    public class HomeController {
    
        private static long visitCount = 0;
    
        @GetMapping("/html/dynamic")
        public String helloHtmlFile(Model model) {
            visitCount++;
            model.addAttribute("visits", visitCount);
            return "hello-visit";
        }
    }
    http://localhost:8080 /html/dynamic - request

    JSONデータ


    Star.java
    @AllArgsConstructor
    @Getter
    @Setter
    public class Star {
        String name;
        int age;
    }
    HomeController
    モデル情報-${アクセス}
    @Controller
    public class HomeController {
    
        @GetMapping("/json/class")
        @ResponseBody
        public Star helloJson() {
            return new Star("유재석", 51);
        }
    }
    コントローラが返すオブジェクトはStringではなくresources/staticであり、Resone Headerが返すStarはアプリケーション/jsonであると判断できます.
    http://localhost:8080 /json/class - request

    + @RestController


    @Controllerと@Responsebodyの組み合わせ-ビューからデータを返さない

    応答の概要