SpringBoot拦截静态资源请求

我们项目中目前用的是SpringBoot1.5.6版本,最近给某个项目做了一个测试页面,地址类似这样:

http://www.10jqka.com.cn/test.html

我们希望发布后,这个测试页面只对内网开放,在公司外不能访问,因此准备用拦截器 WebMvcConfigurerAdapter的addInterceptors方法将这个页面拦截掉。但是用常规的拦截方式,发现不起效。

经过搜索资料,得知:

使用SpringBoot框架的拦截器时,在1.5.x版本下 WebMvcConfigurerAdapter的addInterceptors方法只能拦截控制器方法,直接请求静态资源时,该拦截器不生效。

在SpringBoot2.x下addInterceptors既可以拦截静态资源又可拦截控制器资源。

如果确实要在1.5.6下面拦截,可以通过重新注册MappedInterceptor来实现(代码来自同事YWD):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.handler.MappedInterceptor;

@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {


@Bean
IPInterceptor ipInterceptor() {
return new IPInterceptor();
}

/**
* 非常重要的bean,在springboot1.5.X版本,重新注册它使得静态的资源也需要经过拦截器。
*
* @param ipInterceptor
* @return 新的mappedInterceptor, 用来更换老的inInterceptor
*/
@Bean
MappedInterceptor mappedInterceptor(
IPInterceptor ipInterceptor
) {
return new MappedInterceptor(new String[]{"/**"}, ipInterceptor);
}

@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(ipInterceptor()).addPathPatterns("/**")
.excludePathPatterns("/app/**");
super.addInterceptors(registry);
}
}

里面用到的IPInterceptor.java的代码如下(来自CL同学):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

import static com.myhexin.websocket.utils.IPUtil.inIntranet;

@Component
public class IPInterceptor implements HandlerInterceptor {

private static final Logger logger = LoggerFactory.getLogger(IPInterceptor.class);

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (inIntranet()) {
return true;
} else {
PrintWriter out = null;
JSONObject res = new JSONObject();
res.put("errormsg", "Sorry! You do not have permission to access!");
out = response.getWriter();
out.append(res.toString());
return false;
}
}

@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 {

}
}