SpringBootの特定の応答にヘッダーを追加します
この投稿では、SpringBootアプリケーションの特定の応答にヘッダーを追加する方法について説明します。
SpringBootアプリケーションの特定の応答にカスタムヘッダーを追加する方法はいくつかあります。
1.HttpServletResponseを使用する
特定のコントローラーの応答を設定するには、次のようにします。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletResponse; @RestController @RequestMapping(value = "/app/") public class Controller { @ModelAttribute public void setResponseHeader(HttpServletResponse response) { response.setHeader("Cache-Control", "no-cache"); } @RequestMapping(value = "test") public String test() { return "SUCCESS"; } } |
上記のコードは、コントローラー内のすべてのエンドポイントの応答を設定します。コントローラ内の特定のエンドポイントの応答を設定するために、 HttpServletResponse
引数としてエンドポイントでインスタンスを作成し、 setHeader()
の方法 HttpServletResponse
ヘッダーを設定するためのオブジェクト:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletResponse; @RestController public class Controller { @RequestMapping(value = "execute", method = RequestMethod.GET) public String execute(HttpServletResponse response) { response.setHeader("Cache-Control", "no-cache"); return "SUCCESS"; } } |
2.ResponseEntityの使用
以下に示すように、ヘッダーを追加することもできます ResponseEntity
ビルダー HttpHeaders
クラス。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
import org.springframework.http.HttpHeaders; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class Controller { @RequestMapping(value = "execute") public ResponseEntity<String> execute() { HttpHeaders headers = new HttpHeaders(); headers.add(HttpHeaders.CACHE_CONTROL, "no-cache"); return ResponseEntity.ok() .headers(headers) .body("SUCCESS"); } } |
これで、SpringBootの特定の応答にヘッダーを追加することができます。
続きを読む: