package cn.itsource.interceptor;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
public class LoginInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
Object obj = request.getSession().getAttribute("user_in_session");
if (obj==null){//没有登录,或者登录过期
//跳转到登录页面
response.setContentType("application/json;charset=UTF-8");
response.getWriter().println("{\"success\":false,\"message\":\"toLogin\"}");
//{"success":false,"message":"toLogin"}
return false;
}
return true;//放行
}
}
package cn.itsource.config;
import cn.itsource.interceptor.LoginInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Component
public class LoginInterceptorConfig implements WebMvcConfigurer {
@Autowired
private LoginInterceptor loginInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(loginInterceptor)
.addPathPatterns("/**")
//排除跟登录相关的
.excludePathPatterns("/login")
//排除跟注册相关的 - 不是用axios发送的请求 - cookie用不了【8081-8080】
.excludePathPatterns("/minio")
//排除跟测试相关的 - 反正就是不需要登录就可以访问都要排除
.excludePathPatterns("/swagger-resources/**", "/webjars/**",
"/v2/**", "/swagger-ui.html/**");
}
}