创建一个Interceptor
/**
* @author Wgs
* @version 1.0
* @create:2019/04/14
*/
@Component
public class AuthCheckInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
String token = httpServletRequest.getHeader(Constant.TOKEN_String);
if (StringUtils.isBlank(token)) {
throw new Exception("Header 中缺少 " + Constant.TEMPLATE_TOKE + "!");
}
if (!token.equals(Constant.TOKEN_String)) {
throw new Exception("Header 中 token 错误!");
}
AccessContext.setToken(token);
return true;
}
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
AccessContext.clearAccessKey();
}
}
spring 启动类上配置
@SpringBootApplication
public class MerchantsApplication extends WebMvcConfigurerAdapter {
// 注入拦截器
@Resource
private AuthCheckInterceptor authCheckInterceptor;
public static void main(String[] args) {
SpringApplication.run(MerchantsApplication.class, args);
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 拦截器
registry.addInterceptor(authCheckInterceptor)
// 拦截以merchants开头的url
.addPathPatterns("/merchants/**");
super.addInterceptors(registry);
}
}
拦截以merchants开头的url
/**
* @author Wgs
* @version 1.0
* @create:2019/04/18
*/
@RestController
@RequestMapping("/merchants")
@Slf4j
public class MerchantsCtl {
private final IMerchantsSe merchantsSe;
@Autowired
public MerchantsCtl(IMerchantsSe merchantsSe) {
this.merchantsSe = merchantsSe;
}
/**
* 创建商户
*
* @param createMerchantsRequest
* @return
*/
@RequestMapping("/create")
public Response create(CreateMerchantsRequest createMerchantsRequest) {
log.info("createMerchantsRequest={}", JSON.toJSONString(createMerchantsRequest));
Response merchants = merchantsSe.createMerchants(createMerchantsRequest);
return merchants;
}
/**
* 根据商户id获取商户
*
* @param id
* @return
*/
@RequestMapping("/{id}")
public Response build(@PathVariable("id") Integer id) {
log.info("id={}", id);
Response response = merchantsSe.buildMerchants(id);
return response;
}
@RequestMapping("/drop")
public Response dropPassTemplate(PassTemplate passTemplate) {
log.info("passTemplate={}", passTemplate);
Response response = merchantsSe.dropPassTemplate(passTemplate);
return response;
}
}