menu
書いてる野郎
orebike@gmail.com
とりあえず準備として Spring Starter Project で1個作る。 build.gradile はこんな感じ。
plugins { id 'org.springframework.boot' version '2.1.6.RELEASE' id 'java' } apply plugin: 'io.spring.dependency-management' group = 'com.example' version = '0.0.1-SNAPSHOT' sourceCompatibility = '1.8' configurations { developmentOnly runtimeClasspath { extendsFrom developmentOnly } } repositories { mavenCentral() } dependencies { implementation 'org.springframework.boot:spring-boot-starter-thymeleaf' implementation 'org.springframework.boot:spring-boot-starter-web' implementation 'org.mybatis.spring.boot:mybatis-spring-boot-starter:2.0.1' developmentOnly 'org.springframework.boot:spring-boot-devtools' runtimeOnly 'mysql:mysql-connector-java' testImplementation 'org.springframework.boot:spring-boot-starter-test' }
とりあえず画面が出るコントローラーを1個作る
@Controller @RequestMapping("/hoge") public class HogeController { @RequestMapping("") public String index() { return "hoge/index"; } }
hoge/index.html も作るが適当。
<h1>hoge</h1>
とりあえず DB とか使わないんで抑止
@SpringBootApplication @EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class}) public class UnkoApplication { public static void main(String[] args) { SpringApplication.run(UnkoApplication.class, args); } }
実行して http://localhost:8080/hoge で見れた。
共通処理を作りたいのでその確認のためにもういっちょ作る
@Controller @RequestMapping("/piyo") public class PiyoController { @RequestMapping("") public String index() { return "piyo/index"; } }
piyo/index.html も作る
<h1>piyo</h1>
共通処理を書くための Interceptor を作る。
今回は認証の共通処理を作るつもりなので MyAuthInterceptor を作る。
このように HandlerInterceptor の中の preHandle メソッドを実装する
public class MyAuthInterceptor implements HandlerInterceptor{ @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { return false; } }
HandlerInterceptor を implements しても実装を強制されないのは Java / 基礎 / Interface / デフォルト実装 が存在するからである。
このメソッドの中でとりあえず false を返しておく。
このアプリ全体にこの Interceptor を適用する。
このようにする
@SpringBootApplication @EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class}) public class UnkoApplication { public static void main(String[] args) { SpringApplication.run(UnkoApplication.class, args); } @Bean public MappedInterceptor interceptor() { return new MappedInterceptor( new String[]{"/**"}, myAuthInterceptor()); } @Bean public MyAuthInterceptor myAuthInterceptor() { return new MyAuthInterceptor(); } }
このように書くと設定した範囲、今なら /**
なので全範囲に MyAuthInterceptor を適用される。
試しに hoge/index の画面へ再びアクセスしてみるとレスポンスが真っ白になってしまう。
piyo/index も同様にそうなる。これは preHandle
が false を返すようになっているからである。
やればわかるが true を返すとそのまま Controller へ素通しになる。
これで共通処理の方法もわかったし、とりあえずアプリ全体をガードできることも確認できた。