實現自定義攔截器,實現登錄驗證
package com.hadwinling.myblog.mvc;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* @author HadwinLing
* @version V1.0
* @Package com.hadwinling.myblog.mvc
* @date 2020/7/3 9:36
* 實現自定義攔截器,實現登錄驗證
*/
@Component
public class UriInterceptor implements HandlerInterceptor {
/**
* @param request
* @param response
* @param handler
* @return
* @throws Exception
* 在請求處理之前進行攔截
* 如果是已登錄 放行 返回true
* 如果是沒登陸狀態 不放行 返回false 去登錄
* 自定義對哪些請求進行攔截
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//獲取登錄的Uri
String requestURI = request.getRequestURI();
//登錄請求放心
//根據項目定義需要攔截的請求
if (requestURI.endsWith("/")
||requestURI.endsWith("/index")
||requestURI.endsWith("/user/loginWithNicknameAndPassword")
||requestURI.endsWith("/user/toLoginPage")
||requestURI.endsWith("/user/resetSend")
||requestURI.endsWith("/user/LoginWithTel")){
//如果是登錄請求或者不需要登錄的請求進行放行
return true;
}
//判斷用戶是否已經登錄
HttpSession session = request.getSession();
Object currUser = session.getAttribute("currUser");
if (currUser!=null){
//已登錄
return true;
}
//未登錄 要求用戶去登錄
request.getRequestDispatcher("/user/toLoginPage").forward(request,response);
return false;
}
}
實現自定義mvc配置
package com.hadwinling.myblog.mvc;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* @author HadwinLing
* @version V1.0
* @Package com.hadwinling.myblog.mvc
* @date 2020/7/3 9:25
* 實現自定義mvc配置
*/
@Configuration
public class WebMvc implements WebMvcConfigurer {
@Autowired
private UriInterceptor uriInterceptor;
@Autowired
private AdminUriInterceptor adminUriInterceptor;
/**
* 給指定頁面添加控制器
* @param registry
*/
@Override
public void addViewControllers(ViewControllerRegistry registry) {
//給指定的試圖田間url請求映射
//http://localhost:8080/blog/admin/
registry.addViewController("/admin/").setViewName("/AdminCenter/login");
registry.addViewController("/admin/toLoginPage").setViewName("/AdminCenter/login");
}
/**
* 添加攔截器
* @param registry
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(uriInterceptor)
.addPathPatterns("/**") //表示攔截所有請求
.excludePathPatterns("/user/toLogin","/") //不攔截哪些請求
.excludePathPatterns("/js/**") //靜態資源不攔截
.excludePathPatterns("/css/**")
.excludePathPatterns("/images/**")
.excludePathPatterns("/dist/**")
.excludePathPatterns("/bower_components/**");
}
}