項目參考:詳細參見:《Spring Boot 2精髓:從構建小系統到架構分布式大系統》 第三章 3.6.1節 攔截器

MyWebMvcConfigurer
package com.archibladwitwicke.springboot2.chapter03.configurer;
import com.archibladwitwicke.springboot2.chapter03.intercept.AdminLoginIntercept;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class MyWebMvcConfigurer implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 添加一個攔截器,連接以/admin為前綴的 url路徑
registry.addInterceptor(new AdminLoginIntercept()).addPathPatterns("/admin/**");
}
}
TestAdminController
package com.archibladwitwicke.springboot2.chapter03.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("/admin")
public class TestAdminController {
@RequestMapping("/hello")
@ResponseBody
public String say() {
return "this is a admin page.";
}
}
AdminLoginIntecept
package com.archibladwitwicke.springboot2.chapter03.intercept;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class AdminLoginIntercept implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// 如果已經登錄返回true。
// 如果沒有登錄沒有登錄,可以使用 reponse.send() 跳轉頁面。后面要跟return false,否則無法結束;
// 為了測試,打印一句話
System.out.println("訪問了admin下url路徑。");
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
}
