1.项目结构

Springboot2.1.1下的自定义拦截器而静态资源不能访问的问题-LMLPHP

2.自定义拦截器

public class LoginHandlerlnterceptor implements HandlerInterceptor {
//目标方法执行之前
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
Object loginname = request.getSession().getAttribute("loginname");
if(loginname==null||loginname.equals("")){
//未登录,返回登陆界面
request.setAttribute("msg","没有权限,请先登陆");
//返回登陆page并且相应
// response.sendRedirect("/index.html");
request.getRequestDispatcher("/").forward(request,response);
return false;
}else
{
//已经登陆,放行
return true;
} } @Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { } @Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { }
}

3.拦截器加入mvc

public class Mymvc implements WebMvcConfigurer {
//注册拦截器
@Override
public void addInterceptors(InterceptorRegistry registry) {
//springboot1已经做好了静态资源映射了,可以访问到
registry.addInterceptor(new LoginHandlerlnterceptor()).addPathPatterns("/**").excludePathPatterns("/", "/user/logins", "/login.html").excludePathPatterns("/img/**",
"/css/**", "/webjars/**");
} }

ok!                     还有不明白的可以下面留言

05-23 17:18