实现自定义拦截器,实现登录验证
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/**");
}
}