當要架設需要使用者先登入才能進行其他操作的網站時,
要建立攔截器(HandlerInterceptor)並註冊進Spring MVC中。
首先,建立攔截器:
建立class,繼承HandlerInterceptor這個攔截器介面。在preHandle方法內判定session是否有會員的資訊
@Component
public class AuthorizationInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
System.out.println("---AuthorizationInterceptor preHandle---");
if (request.getSession().getAttribute("emp") != null) {
return true;
} else {
response.sendRedirect(request.getContextPath() + "/login");
return false;
}
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
System.out.println("---AuthorizationInterceptor postHandle---");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
System.out.println("---AuthorizationInterceptor afterCompletion---");
}
}
接著,加入要過濾的請求及排除白名單
建立WebAppConfig這個class,繼承WebMvcConfigurer
addPathPatterns("/*")表示攔截所有請求
excludePathPatterns("/login")表示只讓/login這個視圖名稱的請求通過(白名單)
@Configuration
@EnableWebMvc
@ComponentScan("你的專案名稱")
public class WebAppConfig implements WebMvcConfigurer {
@Autowired
private AuthorizationInterceptor authorizationInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(authorizationInterceptor).
addPathPatterns("/*").excludePathPatterns("/login");
}
}
這樣就能先登入才能做其它事囉!
沒有留言:
張貼留言