先写一个包,interceptor,然后在此包下写一个LoginInterceptor类实现HandlerInterceptor接口。如下:
package com.fan.interceptor;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response,
Object handler) throws Exception {
//如果用户没登录,则跳转,不放行
if(request.getSession().getAttribute("uer") == null){
response.sendRedirect("/admin");//跳转到登录页面
return false;
}
//否则,放行请求
//如果设置为false时,被请求时,拦截器执行到此处将不会继续操作
//如果设置为true时,请求将会继续执行后面的操作
return true;
}
}
第二步:将这个拦截器(过滤网配置到web容器中),写一个WebConfig类实现WebMvcConfigurer接口:
package com.fan.interceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginInterceptor()).addPathPatterns("/admin/**")
.excludePathPatterns("/", "/admin/login", "/admin");
}
}