天天看点

SpringBoot静态资源请求失败,添加拦截器,指定后缀 解决方法

SpringBoot静态资源请求失败

静态资源存放位置为: /resources/static/**

方法一:

1.在pom中添加jar包

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
           

2.application.yml文件中添加配置

spring:
    mvc:
        static-path-pattern: /static/**
           

如需添加配置类, 不能继承WebMvcConfigurationSupport, 应实现WebMvcConfigurer类或自定义配置类, 否则由于WebMvcConfigurationSupport中的addResourceHandlers默认方法会导致静态资源不可访问

方法二:

在配置类中添加urlMapper

@Configuration
public class MyWebConfig extends WebMvcConfigurationSupport {  
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
        super.addResourceHandlers(registry);
    }

}
           

这两种方法都不能再添加配置类, 指定url请求后缀了, 如果需要指定请求后缀, 可增加Controller基类, 其他Controller继承该类

@RequestMapping("**.html") // 只处理.html后缀的请求
public class BaseController {
}
           
@Controller
public class IndexController extends BaseController {
}
           

添加拦截器

1.配置类中注册拦截器

@Configuration
public class MyWebConfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new GlobalInterceptor()).addPathPatterns("/**/*.html");
    }
}
           

2.添加拦截器类

public class GlobalInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(
            HttpServletRequest request, 
            HttpServletResponse response, Object handler) throws Exception {
        System.out.println("---------------request start--------------");
        return true;
    }

}