Spring boot 配置拦截器
拦截器配置
@Configuration
public class SpringWebConfig extends WebMvcConfigurerAdapter {
@Bean AuthInterceptor interfaceAuthInterceptor() { return new AuthInterceptor(); } @Override public void addInterceptors(InterceptorRegistry registry) { InterceptorRegistration addInterceptor = registry.addInterceptor(interfaceAuthInterceptor()); // 排除配置 addInterceptor.excludePathPatterns("/login","/user/isLoginValid","/getuser"); // 拦截配置 addInterceptor.addPathPatterns("/**"); } }
拦截器
public class AuthInterceptor extends HandlerInterceptorAdapter {
@Autowired
LoginService loginService;
private static final Logger logger = LoggerFactory.getLogger(AuthInterceptor.class);
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
logger.info("token=={}", request.getParameter("token"));
try {
UserRelationInfo userRelationInfo = null;
if(StringUtils.isEmpty(request.getParameter("token"))){
userRelationInfo = new UserRelationInfo();
userRelationInfo.setResultEnum(ResultEnum.SUCCESS);
userRelationInfo.setUid(119);
userRelationInfo.setUsercode("10003001");
UserEntity userEntity = new UserEntity();
userEntity.setUserid(119);
userEntity.setUsercode("10003001");
userEntity.setPassword("e10adc3949ba59abbe56e057f20f883e");
userRelationInfo.setUserEntity(userEntity);
userRelationInfo.setCampusid(1);
userRelationInfo.setSchoolid(4);
userRelationInfo.setTermid(8);
userRelationInfo.setUsertype((byte) 2);
request.setAttribute("user", userRelationInfo);
return true;
} else {
userRelationInfo = loginService.isLoginValid(request, response);
request.setAttribute("user", userRelationInfo);
if( userRelationInfo.getResultEnum() != ResultEnum.SUCCESS ){
response.setContentType("application/json; charset=UTF-8");
Map result = new HashMap<>();
result.put("code",userRelationInfo.getResultEnum().getCode());
result.put("message",userRelationInfo.getResultEnum().getMsg());
response.getWriter().println(JSON.toJSONString(result));
return false;
} else {
return true;
}
}
} catch (Exception e) {
e.printStackTrace();
logger.info("isLoginValid error::" + e);
}
return false;
}
}