spring-boot-资源处理

原文链接: http://www.cnblogs.com/zhangjianbin/p/10077256.html

WebMvcConfigurerAdapter 使用

1.实现 HandlerInterceptorAdapter

2.添加拦截器
重写WebMvcConfigurerAdapter中的addInterceptors方法

@Configuration
public class MyWebMvcConfigurerAdapter extends WebMvcConfigurerAdapter {


    /**
     * 配置静态访问资源
     *
     * addResourceLocations指的是文件放置的目录,
     * addResoureHandler指的是对外暴露的访问路径
     *
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //自定义项目内目录
        registry.addResourceHandler("/my/**").addResourceLocations("classpath:/my/");
        //指向外部目录
        //registry.addResourceHandler("/my/**").addResourceLocations("file:E:/my/");

        super.addResourceHandlers(registry);
    }

    /**
     * 以前要访问一个页面需要先创建个Controller控制类,在写方法跳转到页面
     * 在这里配置后就不需要那么麻烦了,
     *
     * 直接访问http://localhost:8080/toLogin就跳转到login.html页面了
     *
     * @param registry
     */
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/toLogin").setViewName("login");
        super.addViewControllers(registry);
    }

    /**
     * 拦截器
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // addPathPatterns 用于添加拦截规则
        // excludePathPatterns 用户排除拦截
        registry.addInterceptor(new MyInterceptor()).addPathPatterns("/**").excludePathPatterns("/toLogin","/login");
        super.addInterceptors(registry);
    }
}

使用Spring Boot的默认配置方式,提供的静态资源映射如下:

- classpath:/META-INF/resources    
- classpath:/resources    
- classpath:/static
- classpath:/public

转载于:https://www.cnblogs.com/zhangjianbin/p/10077256.html

猜你喜欢

转载自blog.csdn.net/weixin_30814329/article/details/94870578