27.Spring-Boot中拦截器中静态资源的处理(踩过坑)以及Spring mvc configuring拓展介绍

一.springboot中对静态资源的处理

 默认情况下,springboot提供存放放置静态资源的文件夹:

 /static 

/public  

/resources 

/META-INF/resources

对于maven项目即就是存在src/main/resources 文件夹下。

​ 如图:static文件夹就是springboot中默认的文件夹

在页面中这样写路径<link href="themes/bootstrap.min.css" rel="stylesheet" type="text/css"/>这块就不用写static文件夹了。

于此同时我们也可以修改springboot默认的存放静态文件夹存放路径用 spring.mvc.static-path-pattern=/resources/** 。

在springboot中添加拦截器是不会认springboot中的静态文件夹的路径的,所以在设置拦截器的时候应该从springboot默认的静态文件算起。

具体代码如下:

静态文件存放路径还如上图

1.定义拦截器

package com.niugang.filter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
public class LogInterceptor implements HandlerInterceptor {
private static Logger logger = LoggerFactory.getLogger(LogInterceptor.class);
    /**
     * 执行拦截器之前
     */
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
logger.info("interceptor....在执行前...url:{}", request.getRequestURL());
return true; //返回false将不会执行了
}

      /**
* 调用完处理器,渲染视图之前
*/
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
logger.info("interceptor.......url:{}", request.getRequestURL());
}


@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
}
}

2.配置拦截器

package com.niugang.config;
import java.util.concurrent.TimeUnit;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.CacheControl;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import com.niugang.filter.LogInterceptor;
@Configuration
@EnableWebMvc
public class MvcConfig extends WebMvcConfigurerAdapter {
/**
* 授权拦截的路径 addPathPatterns:拦截的路径 excludePathPatterns:不拦截的路径
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LogInterceptor()).addPathPatterns("/**").excludePathPatterns("/login/**",
"/static/*");
super.addInterceptors(registry);
}

     /**
* 修改springboot中默认的静态文件路径
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//addResourceHandler请求路径
//addResourceLocations 在项目中的资源路径
//setCacheControl 设置静态资源缓存时间
registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/")
.setCacheControl(CacheControl.maxAge(1, TimeUnit.HOURS).cachePublic());
super.addResourceHandlers(registry);
}
}

3.页面引入

<link href="static/themes/bootstrap.min.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="static/script/jquery.min.js" ></script>
<!--layer弹出框-->
<link rel="stylesheet" href="static/script/layer/mobile/need/layer.css" type="text/css">
<script type="text/javascript" src="static/script/layer/layer.js" ></script>

这样就可以正常访问了。

二。spring mvc configuring配置介绍

MVC Java config和MVC名称空间提供了类似的默认配置,可以覆盖DispatcherServlet默认配置。目标是让大多数应用程序不必创建相同的配置,并为配置Spring MVC提供更高级别的构造,而Spring MVC作为一个简单的起点,并且不需要事先知道底层配置的知识。

您可以根据您的偏好选择MVC Java config或MVC名称空间。此外,您还将看到,在MVC Java配置下,更容易看到底层配置,并直接对创建的Spring MVC bean进行细粒度定制。

1.MVC Java配置

启用MVC Java配置需要@EnableWebMvc 和 @Configuration注解在类上

@Configuration
@EnableWebMvc
public class WebConfig {


}


上面的配置如XML中的

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<mvc:annotation-driven/>
</beans>

开启上面配置,底层其实开启了很多默认的配置,如果消息转换,时间格式化,字段检验与转化。

2.自定义配置

要自定义Java的默认配置,只需实现WebMvcConfigurer接口。或者更可能扩展类WebMvcConfigurerAdapter并覆盖您需要的方法推荐使用重写WebMvcConfigurerAdapter:

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
// Override configuration methods...
}


这样你可以重写很多方法,就如刚才代码,重写了配置静态资源,和添加拦截器。

具体其他的方法可以看源码注释

三:HTTP Cache 对静态资源的支持

静态资源应该使用适当的“Cache-Control”和有条件的标题来实现最佳性能。配置ResourceHttpRequestHandler用于服务静态资源,不仅可以通过读取文件的元数据来编写“Last-Modified”的标题,而且如果配置正确,还可以“Cache-Control”头。

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**")
.addResourceLocations("/public-resources/")
.setCacheControl(CacheControl.maxAge(1, TimeUnit.HOURS).cachePublic());
}
}

     

 微信公众号

 

 

原文地址:https://www.cnblogs.com/niugang0920/p/12194915.html