0
0

サーバーからクライアントに配信するResponseデータを作成する3つの方法

Posted at

1. 静的リソース

  • ウェブブラウザに静的なHTML、css、jsを提供するときは静的リソースを使用する。
  • src/main/resourcesはリソースを保管する場所であり、class pathの開始経路である。
  • Spring Bootは、class pathの次のディレクトリにある静的リソースを提供する。
    • /static , /public , /resources , /META-INF/resources

    下記の経路にファイルが入っていれば
    src/main/resources/static/basic/hello-form.html
    ウェブブラウザで以下のように実行すればよい。
    http://localhost:8080/basic/hello-form.html

2. View Template

  • ウェブブラウザに動的なHTMLを提供するときは、ビューテンプレートを使用する。

  • static/main/resources/templatesにビューテンプレートを保管する。

  • 一般的にHTML を動的に生成する用途で使用しますが、ビューテンプレートが作れるものなら何でも可能である。

    html以下の経路にビューテンプレートがあり
    src/maiΩn/resources/templates/response/hello.html
    
    <!DOCTYPE html>
    <html xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    <p th:text="${data}">empty</p>
    </body>
    </html>
    
    以下のようにコントローラが作られていれば
    @RequestMapping("/response-view")
    public String responseView(Model model){
        model.addAttribute("data", "hello!");
        return "response/hello";
    }
    
    ウェブブラウザで以下のように実行すればよい。
    http://localhost:8080/response-view
    
    コントローラーを作成する他の方法もある。
    @RequestMapping("/response-view")
    public ModelAndView responseView() {
        ModelAndView mav = new ModelAndView("response/hello")
                .addObject("data", "hello!");
    
        return mav;
    }
    

3. HTTPメッセージの使用

  • HTTP APIを提供する場合にはHTMLではなくデータを伝達しなければならないため、HTTPメッセージボディにJSONと同じ形式でデータを直接入力して送る。

3.1.JSONの場合

    @ResponseBody
    @GetMapping("/response-body-string")
    public HelloData responseBodyJson() {
        HelloData helloData = new HelloData();
        helloData.setUsername("userA");
        helloData.setAge(20);
        return helloData;
    }
他の方法もある。
@GetMapping("/response-body-string-v1")
public ResponseEntity<HelloData> responseBodyJsonV1() {
    HelloData helloData = new HelloData();
    helloData.setUsername("userA");
    helloData.setAge(20);
    return new ResponseEntity<>(helloData, HttpStatus.OK);
}

3.2.単純テキストの場合

@ResponseStatus(HttpStatus.OK)
@ResponseBody
@GetMapping("/response-body-string")
public String responseBody() {
    return "ok";
}

// 動的にResponseStatusを変更したい場合は、その他の方法 > Responsity Entity を参考にして使用すればよい。
他の方法もある。
@GetMapping("/response-body-string-v1")
public void responseBodyV1(HttpServletResponse response) throws IOException {
    response.getWriter().write("ok");
}

@GetMapping("/response-body-string-v2")
public ResponseEntity<String> responseBodyV2(HttpServletResponse response) throws IOException {
    return new ResponseEntity<>("ok", HttpStatus.OK);
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0