1.获取拦截器
package cn.tedu.store.interceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.web.servlet.HandlerInterceptor;
public class LoginInterceptor implements HandlerInterceptor{
/**
* 拦截器
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
//获取哦HttpSession对象
HttpSession session = request.getSession();
//判断session总是否由登录信息
if(session.getAttribute("uid") == null) {
//没有登录信息,则重定向到登录页
response.sendRedirect("/web/login.html");
//执行拦截
return false;
}
//方行
return true;
}
}
2.配置拦截器:
package cn.tedu.store.config;
import java.util.ArrayList;
import java.util.List;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import cn.tedu.store.interceptor.LoginInterceptor;
//表示他是一个配置类
@Configuration
public class InterceptorConfigurer implements WebMvcConfigurer{
//拦截器
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 创建拦截器对象
HandlerInterceptor interceptor = new LoginInterceptor();
// 白名单
List<String> patterns = new ArrayList<>();
patterns.add("/bootstrap3/**");
patterns.add("/css/**");
patterns.add("/js/**");
patterns.add("/images/**");
patterns.add("/web/register.html");
patterns.add("/web/login.html");
patterns.add("/users/reg");
patterns.add("/users/login");
// 注册拦截器
registry.addInterceptor(interceptor)
.addPathPatterns("/**")
.excludePathPatterns(patterns);
}
}