一:拦截器
1.定义拦截器
@Component
public class MyIntercepter implements HandlerInterceptor {
@Override
//原始方法调用前执行的内容,返回值为true表示放行,返回值为false表示不放行
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String token = request.getHeader("token");
if("".equals("token")||token ==null){
Result result = new Result("您没有传token", 403, null);
response.getWriter().write(result.toString());
return false;
}
if(!token.equals(Constants.TOKEN)){
Result result = new Result("您传的参数有误", 401, null);
response.getWriter().write(result.toString());
return false;
}
return true;
}
}
2.配置拦截器
@Configuration
public class MyConfig implements WebMvcConfigurer {
/**
* 配置拦截规则与注入拦截器
* @param registry
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
// addPathPattern 添加拦截规则 /** 拦截所有包括静态资源
// excludePathPattern 排除拦截规则 所以我们需要放开静态资源的拦截
registry.addInterceptor(new MyIntercepter())
.addPathPatterns("/members/**","/managers/**")
.excludePathPatterns("/css/**", "/fonts/**", "/images/**", "/js/**");
}
}
二:过滤器
1.定义过滤器
@WebFilter(filterName = "MyFilter", urlPatterns = {"/members/*","/managers/*"})
public class MyFilter implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
String token = request.getHeader("token");
if ("".equals(token) || token == null) {
Result result = new Result("您没有传token", 403, null);
response.getWriter().write(result.toString());
return;
}
if (!token.equals(Constants.TOKEN)) {
Result result = new Result("您传的token有误", 401, null);
response.getWriter().write(result.toString());
return;
}
//放行
filterChain.doFilter(request, response);
}
}
2.配置过滤器
@SpringBootApplication
@ServletComponentScan
public class MpdemoApplication {
public static void main(String[] args) {
SpringApplication.run(MpdemoApplication.class, args);
}
}
三:AOP