[Spring入門]#02 Spring Web開発基礎


授業を受けながら金ヨンヒョンのメモを取る.

静的コンテンツ


Spring Bootは静的コンテンツを自動的にサポートします.

Example


静的ファイルの作成-hello-static



ファイルを作成し、プロジェクトを実行します.

"Spring入门-学习コード的Spring Boot,Web MVC,DB动作技术"



これにより、パスにファイル名だけが少なくとも自動的に返されます.
ただし、静的ファイルのプログラミングはできません.
要求が現在のパスである場合、スプリングガイドはまずコントローラでファイルを検索します.
ない場合はresources:statc/hello-staticを検索して返します.

MVCとテンプレートエンジン

  • MVC:型番、ビュー、コントローラ
  • Example


    helloController

    ...
    @GetMapping("hello-mvc")
        public String helloMvc(@RequestParam(value = "name",required = true) String name, Model model){
            model.addAttribute("name",name);
            return "hello-template";
        }
    「hello-mvc」を使用すると、「hello-mtemplate」ファイルが返されます.
    パラメータをRequestParamで渡します.(@RequestParam(value = "name",required = true)は必須であり、nameをパラメータとして渡す.

    templates/hello-template

    <!DOCTYPE html>
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    <body>
    <p th:text="'안녕하세요. ' +${name}">helo! empty</p>
    </body>
    </html>

    " http://localhost:8080/hello-static.html "



    API


    ResponseBodyオブジェクトに戻る

    Example1


    静的コンテンツの他にHTMLかAPIかに分かれています.
    @GetMapping("hello-string")
    @ResponseBody
    public String helloString(@RequestParam("name") String name){
            return "hello " + name;
    }
    @ResponseBodyの使用
    テキスト内容を
  • HTTP Bodyに直接戻す
    HttpMessageConverter代替
  • ViewResolver
  • デフォルト文字処理:StringHttpMessageConverter
  • デフォルトオブジェクト処理:MappingJackson 2 HttpMessageConverter
  • バイト処理など、他の複数のHttpMessageConverter
  • がデフォルトで登録されている

    Example2


    static classを使用するとclassでクラスを使用できます.
    ...
        @GetMapping("hello-api")
        @ResponseBody
        public Hello helloApi(@RequestParam("name") String name){
            Hello hello = new Hello();
            hello.setName(name);
            return hello;
        }
    
        static class Hello{
            private String name;
    		
            // getter와 setter은 java bean 표준 방식이다. (프로퍼티 접근 방식)
            public String getName() {
                return name;
            }
    
            public void setName(String name) {
                this.name = name;
            }
        }

    このようにjson形式で出てきます!
    デフォルトのポリシーは、オブジェクトをjsonとして作成して返すことです.