0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【SpringBoot】共通処理を行うfilterについて

Posted at

Filterとは

  • FE↔︎BEの間で実行される処理をまとめたクラス
    • リクエスト→filter→controller→service→controller→filter→レスポンス
    • リクエスト後にコントローラを呼ぶ前、リクエストを横取りして処理
  • ログ出力や認証など、API実行時に共通して行いたい処理を実行するのに便利

ディレクトリ構成

com.sample.demo
 ├─ DemoApplication.java
 ├─ controller
 │   └─ Controller.java
 ├─ service
 │   └─ Service.java
 └─ filter
     └─ DemoFilter.java  // ココ!

使用例

DemoApplication.java
// 起動クラス
@SpringBootApplication
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}
DemoFilter.java
// フィルタークラス
@Component
public class DemoFilter implements Filter {  // Filterクラスを継承する
    @Override
    public void doFilter(
        ServletRequest request,  // リクエスト情報
        ServletResponse response,  // レスポンス情報
        FilterChain chain  // 次の処理への通路
    ) throws IOException, ServletException {
        // HTTP特有の情報が取れるようにキャスト
        HttpServletRequest req = (HttpServletRequest) request;

        // API前後にログを出力
        System.out.println("Filter 開始: " + req.getMethod() + " " + req.getRequestURI());

        // 次のフィルターへ(無ければcontroller)
        chain.doFilter(request, response);

        System.out.println("Filter 終了");
    }
}
Controller.java
// コントローラクラス
@RestController
public class Controller {

    // クラス変数
    private final Service service;
    pubric Service(Service service) {
        this.service = service;
    }

    // メッセージを取得するAPI
    @GetMapping("/get/message")
    public String getMessage() {
        return service.getMessage();
    }
}
Service.java
// サービスクラス
@Service
public class Service {

    // メッセージを取得するAPI
    public String getMessage() {
        return "Hello cat.";
    }
}

注意点

  • filterは必須処理ではないので必要であれば使用する
  • APIが増えたりチーム開発をする場合は連携が必要になる
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?