在這篇筆記 《SpringMVC登錄驗(yàn)證從有到無》中說明了如何通過SpringMVC去實(shí)現(xiàn)了登錄驗(yàn)證功能包蓝。但是這種方式適用于后臺管理系統(tǒng),在前臺應(yīng)用中双揪,有很多接口不需要登錄也可以訪問,如果要在攔截器中去一一判斷就顯得太麻煩不夠優(yōu)雅了。
優(yōu)雅的實(shí)現(xiàn)方式 —— 注解
1.創(chuàng)建注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface LoginCheck {
}
2.在Controller的方法上使用@LoginCkeck注解
@RequestMapping(value = "/toHome", method = RequestMethod.GET)
@LoginCheck
public String toHome() {
return "home";
}
3.在攔截器進(jìn)行注解校驗(yàn)
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
super.preHandle(request, response, handler);
HandlerMethod handlerMethod = (HandlerMethod) handler;
Method method = handlerMethod.getMethod();
if (method.isAnnotationPresent(LoginCheck.class)) {
// 使用@LoginCheck注解监憎,則進(jìn)行登錄驗(yàn)證
HttpSession session = request.getSession();
User user = (User) session.getAttribute(Constans.USER);
if (user != null) {
return true;
}
// 不符合條件的跳轉(zhuǎn)到登錄界面
// response.sendRedirect("/mall-console/login.do");
// 解決重定向登錄界面在iframe頁面顯示不在top頁面顯示的問題
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<script>");
out.println("window.open('/mall-console/login.do', '_top')");
out.println("</script>");
out.println("</html>");
return false;
}
return true;
}
4.總結(jié)
不需要任何的url字符串的匹配,僅僅通過判斷方法是否使用@LoginCheck注解婶溯,是不是更加優(yōu)雅鲸阔?仔細(xì)看看,靜態(tài)資源的訪問問題也不存在了迄委。