1、自定義攔截器,實現HandlerInterceptor或者繼承WebMvcConfigurerAdapter
import com.alibaba.fastjson.JSON;
import com.trgis.www.manage.entity.TRUser;
import com.trgis.www.manage.service.TRUserService;
import com.trgis.www.util.BeanUtil;
import com.trgis.www.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;
/**
* @Author: zhao
* @CreateDate: 2019/10/17$ 18:57$
*/
@Controller
public class UserTokenInterceptor implements HandlerInterceptor{
@Autowired
private TRUserService trUserService;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
HttpSession session = request.getSession();
TRUser user = (TRUser) session.getAttribute("user");
if (BeanUtil.isEmpty(user)) {
Result result = new Result();
result.setError("登錄超時", -1);
returnResult(result, response);
return false;
} else {
Result result = new Result();
String username = user.getUsername();
TRUser trUser = trUserService.findByUsername(username);
if (BeanUtil.isNotEmpty(trUser)) {
if (!trUser.getPassword().equals(user.getPassword())) {
result.setError("用戶密碼已更改");
returnResult(result, response);
return false;
}
} else {
result.setError("用戶不存在");
returnResult(result, response);
return false;
}
}
return true;
}
private void returnResult(Result result, HttpServletResponse response) {
PrintWriter writer = null;
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json;charset=UTF-8");
String json = JSON.toJSONString(result);
try {
writer = response.getWriter();
writer.print(json);
} catch (Exception e) {
} finally {
if (null != writer) {
writer.close();
}
}
}
}
2、配置靜態資源、以及自定義攔截器對部分接口不攔截,配置如下
import com.trgis.www.framework.interceptor.UserTokenInterceptor;
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.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
/**
* @Author: zhao
* @CreateDate: 2019/10/17$ 18:50$
*/
@Component
public class WebMvcConfig extends WebMvcConfigurationSupport{
@Autowired
private UserTokenInterceptor userTokenInterceptor;
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
//第一個方法設置訪問路徑前綴,第二個方法設置資源路徑
registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");
registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
}
@Override
protected void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(userTokenInterceptor)
//addPathPatterns 用於添加攔截規則
.addPathPatterns("/**")
//項目啓動測試接口
.excludePathPatterns("/")
// 靜態資源
.excludePathPatterns("/static/**")
// SwaggerUI
.excludePathPatterns("/swagger-ui.html","/v2/api-docs","/webjars/**","/swagger-resources/**")
// 用戶登錄不攔截
.excludePathPatterns("/login")
// public爲前綴的訪問都取消驗證
.excludePathPatterns("/public/**");
}
}
3、配置web靜態文件,訪問不帶static前綴
說明:配置文件中application.yml不用配置spring.mvc.static-path-pattern及spring.resources.static-locations
@Component
public class TokenInterceptorConfig extends WebMvcConfigurationSupport {
private ApplicationContext applicationContext;
/**
* 配置攔截器的Bean
* @return
*/
@Autowired
private OperationLogInterceptor operationLogInterceptor;
@Autowired
private SessionInterceptor sessionInterceptor;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**")
.addResourceLocations("classpath:/static/")
.addResourceLocations("classpath:/resources/")
.addResourceLocations("classpath:/META-INF/resources/")
.addResourceLocations("classpath:/templates/");
registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
super.addResourceHandlers(registry);
}
/**
* c重寫addInterceptors方法,註冊攔截器
* @param registry
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 多個攔截器組成一個攔截器鏈
registry.addInterceptor(sessionInterceptor).addPathPatterns("/**")
.excludePathPatterns(
"/*.html", "/**/*.ico", // 配置static根目錄文件訪問
"/assets/**", "/css/**", "/html/**", "/images/**", "/InHouseApp/**", "/js/**", "/libs/**", "/mail/**", "/res/**", "/ueditor1_4_3_3/**", "/zhaopin/**", // 配置static根目錄文件夾下的文件訪問
"/", "/static/**", // 靜態資源
"/doc.html**","/v2/api-docs","/webjars/**","/swagger-resources","/swagger-ui.html", // SwaggerUI
"/login","/ajaxLogin", // 用戶登錄
"/editor","/index","/error","/index.html","/downFile","/public/**"
);
registry.addInterceptor(operationLogInterceptor).addPathPatterns("/**")
.excludePathPatterns(
"/*.html", "/**/*.ico", // 配置static根目錄文件訪問
"/assets/**", "/css/**", "/html/**", "/images/**", "/InHouseApp/**", "/js/**", "/libs/**", "/mail/**", "/res/**", "/ueditor1_4_3_3/**", "/zhaopin/**", // 配置static根目錄文件夾下的文件訪問
"/", "/static/**", // 靜態資源
"/doc.html**","/v2/api-docs","/webjars/**","/swagger-resources","/swagger-ui.html", // SwaggerUI
"/login","/ajaxLogin", // 用戶登錄
"/editor","/index","/error","/index.html","/downFile","/public/**",
"/logout"
);
super.addInterceptors(registry);
}
}