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?

More than 3 years have passed since last update.

継承機能を組み込んでみた。

Posted at

問題

ログイン情報取得のコードを各コントローラーで読み込む必要があるが、コードが冗長化してしまう。

@Controller
public class TestController{
  @GetMapping("/index")
  public String index(Model model) {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    if (auth.getPrincipal() instanceof DbUserDetails) {
      int loginUserId = ((DbUserDetails) auth.getPrincipal()).getDbaccount().getID();
      String userNickname = ((DbUserDetails) auth.getPrincipal()).getDbaccount().getNICKNAME();
      String mainImage = ((DbUserDetails) auth.getPrincipal()).getDbaccount().getMAIN_IMAGE();
      model.addAttribute("loginUserId", loginUserId);
      model.addAttribute("loginUserNickname", userNickname);
      model.addAttribute("loginUserMainImage", mainImage);
    }
  }
}

仮説

ログイン情報取得のコードをモジュール化し、継承することでコード量を減らすことができるのではないか。


実装①

ログイン情報取得コードをCommonクラスとしてモジュール化する。

public class Common {
  protected int loginProcessing(Model model) {
      Authentication auth = SecurityContextHolder.getContext().getAuthentication();
      if (auth.getPrincipal() instanceof DbUserDetails) {
          int loginUserId = ((DbUserDetails) auth.getPrincipal()).getDbaccount().getID();
          String userNickname = ((DbUserDetails) auth.getPrincipal()).getDbaccount().getNICKNAME();
          String mainImage = ((DbUserDetails) auth.getPrincipal()).getDbaccount().getMAIN_IMAGE();
          model.addAttribute("loginUserId", loginUserId);
          model.addAttribute("loginUserNickname", userNickname);
          model.addAttribute("loginUserMainImage", mainImage);
          return loginUserId;
      }
      return 0;
  }
}

実装②

@Controller
public class TestController extends Common {
  @GetMapping("/index")
  public String index(Model model) {
      /* 認証したログインユーザー情報を取得するメソッドを実行(Common.javaのloginProcessingメソッド) */
      loginUserId = loginProcessing(model);
  }
}

結果

モジュール化したCommonクラスを継承することで、各コントローラーに記載するコード量を減らすことができた。他の箇所でも継承を活用すれば、記述量を減らすことが実現できる。

0
0
1

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?