1.在spring boot配置文件application.properties中添加要拦截的链接
com.url.interceptor=/user/test
2.编写拦截器代码 ,创建UrlInterceptorUtil 类
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Properties; @Component
public class UrlInterceptorUtil extends HandlerInterceptorAdapter { private String noCheckUrls;
private static Properties props ; @Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
String url=request.getRequestURI();
Resource resource = new ClassPathResource("/application.properties");//
props = PropertiesLoaderUtils.loadProperties(resource);
noCheckUrls=props.getProperty("com.url.interceptor","");
if(!noCheckUrls.contains(url)){
return true;
}
HttpSession session=request.getSession();
//业务逻辑处理
if (session.getAttribute("User")==null){ response.sendRedirect("/index");
return false;
}
return true;
} @Override
public void postHandle(HttpServletRequest request,
HttpServletResponse response, Object o, ModelAndView mav)
throws Exception {
// System.out.println("postHandle");
} @Override
public void afterCompletion(HttpServletRequest request,
HttpServletResponse response, Object o, Exception excptn)
throws Exception {
// System.out.println("afterCompletion");
}
}
3.配置spring boot拦截
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
//标注此文件为一个配置项,spring boot才会扫描到该配置。该注解类似于之前使用xml进行配置
@Configuration
public class CustomWebMvcConfigurerAdapter extends WebMvcConfigurerAdapter {
@Override
public void addInterceptors(InterceptorRegistry registry) {
//对所有的请求进行拦截
registry.addInterceptor(new UrlInterceptorUtil()).addPathPatterns("/**");
}
}