ResourceHandlerRegistry
/
ResourceHandlerRegistration
是
Spring MVC
的概念模型类,二者配合使用。
ResourceHandlerRegistry
用于保存服务静态资源图片,
css
文件或者其他文件的资源处理器(
resource handler
)的注册信息,而
ResourceHandlerRegistration
就表示这样的"注册信息",它还包含了对头部缓存的设置,用于优化浏览器中资源的加载效率。
ResourceHandlerRegistry
/
ResourceHandlerRegistration
所管理的静态资源可以是
web
应用根路径下的资源,但不限于此,也可以是
classpath
上的资源,文件系统的资源或者其他。
可以认为一个
ResourceHandlerRegistry
组合管理了多个
ResourceHandlerRegistration
对象。
ResourceHandlerRegistry
的典型用法是被某个
WebMvcConfigurer
实现类用于配置静态资源服务,使用例子如下所示 :
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
* 静态资源文件映射配置
* @param registry
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/repo/**").addResourceLocations("file:/tmp/");
registry.addResourceHandler("/my-static/**").addResourceLocations("classpath:/my-static/");
当每次调用registry.addResourceHandler()
时,实际上它会创建一个ResourceHandlerRegistration
对象,然后将该对象放到自己的注册表管理起来,函数参数pathPatterns
表示要映射到URL pattern
, 可以传递多个要映射到的URL pattern
。如下所示 :
* Add a resource handler for serving static resources based on the specified URL path patterns.
* The handler will be invoked for every incoming request that matches to one of the specified
* path patterns.
* 增加一个基于指定的URL路径模式服务静态资源的资源处理器
* Patterns like "/static/**" or "/css/{filename:\\w+\\.css}" are allowed.
* pathPatterns 表示要映射到URL pattern, 可以传递多个要映射到的 URL pattern
* See org.springframework.util.AntPathMatcher for more details on the syntax.
* @return a ResourceHandlerRegistration to use to further configure the
* registered resource handler
public ResourceHandlerRegistration addResourceHandler(String... pathPatterns) {
ResourceHandlerRegistration registration = new ResourceHandlerRegistration(pathPatterns);
this.registrations.add(registration);
return registration;
而当调用addResourceLocations()
时,ResourceHandlerRegistration
对象其实接受了一组资源路径,可能来自classpath
,也可能来自文件系统,然后它将这些路径记录下来。如下所示 :
* Add one or more resource locations from which to serve static content.
* 增加一个或者多个资源位置,所服务的静态资源会来自于这些资源位置。每一个资源位置可以使
* classpath 路径(classpath:/开头),也可能是本地文件系统路径(file:/开头)。
* 这些资源位置上的静态资源都会映射到本注册器所被设置的URL路径模式(pattern)上。
* Each location must point to a valid directory. Multiple locations may
* be specified as a comma-separated list, and the locations will be checked
* for a given resource in the order specified.
* For example, {"/", "classpath:/META-INF/public-web-resources/"}
* allows resources to be served both from the web application root and
* from any JAR on the classpath that contains a
* /META-INF/public-web-resources/ directory, with resources in the
* web application root taking precedence.
* For org.springframework.core.io.UrlResource URL-based resources
* (e.g. files, HTTP URLs, etc) this method supports a special prefix to
* indicate the charset associated with the URL so that relative paths
* appended to it can be encoded correctly, e.g.
* [charset=Windows-31J]http://example.org/path.
* @return the same ResourceHandlerRegistration instance, for
* chained method invocation
public ResourceHandlerRegistration addResourceLocations(String... resourceLocations) {
this.locationValues.addAll(Arrays.asList(resourceLocations));
return this;
最后生成静态资源处理器(resource handler
)时,会用到上面提到的这些URL pattern
和资源路径resource locations
。
当应用开发人员通过上面的registry.addResourceHandler("/repo/**").addResourceLocations("file:/tmp/")
这种方式配置完静态资源映射关系之后,这些关系会被ResourceHandlerRegistry registry
对象记录下来。然后在应用启动过程中,Spring MVC
配置执行阶段,具体来讲,是bean resourceHandlerMapping
实例化过程中,这些信息会被使用,如下代码所示 :
* Return a handler mapping ordered at Integer.MAX_VALUE-1 with mapped
* resource handlers. To configure resource handling, override
* #addResourceHandlers.
@Bean
@Nullable
public HandlerMapping resourceHandlerMapping() {
Assert.state(this.applicationContext != null, "No ApplicationContext set");
Assert.state(this.servletContext != null, "No ServletContext set");
ResourceHandlerRegistry registry = new ResourceHandlerRegistry(this.applicationContext,
this.servletContext, mvcContentNegotiationManager(), mvcUrlPathHelper());
addResourceHandlers(registry);
AbstractHandlerMapping handlerMapping = registry.getHandlerMapping();
if (handlerMapping == null) {
return null;
handlerMapping.setPathMatcher(mvcPathMatcher());
handlerMapping.setUrlPathHelper(mvcUrlPathHelper());
handlerMapping.setInterceptors(getInterceptors());
handlerMapping.setCorsConfigurations(getCorsConfigurations());
return handlerMapping;
从上面代码来看,通过registry.getHandlerMapping()
方法调用,静态资源映射注册信息表ResourceHandlerRegistry
被最终转换成最终要使用的HandlerMapping
对象。其代码如下所示 :
* Return a handler mapping with the mapped resource handlers; or null in case
* of no registrations.
@Nullable
protected AbstractHandlerMapping getHandlerMapping() {
if (this.registrations.isEmpty()) {
return null;
Map<String, HttpRequestHandler> urlMap = new LinkedHashMap<>();
for (ResourceHandlerRegistration registration : this.registrations) {
for (String pathPattern : registration.getPathPatterns()) {
ResourceHttpRequestHandler handler = registration.getRequestHandler();
if (this.pathHelper != null) {
handler.setUrlPathHelper(this.pathHelper);
if (this.contentNegotiationManager != null) {
handler.setContentNegotiationManager(this.contentNegotiationManager);
handler.setServletContext(this.servletContext);
handler.setApplicationContext(this.applicationContext);
try {
handler.afterPropertiesSet();
catch (Throwable ex) {
throw new BeanInitializationException("Failed to init ResourceHttpRequestHandler", ex);
urlMap.put(pathPattern, handler);
SimpleUrlHandlerMapping handlerMapping = new SimpleUrlHandlerMapping();
handlerMapping.setOrder(this.order);
handlerMapping.setUrlMap(urlMap);
return handlerMapping;
ResourceHandlerRegistry/ResourceHandlerRegistration是Spring MVC的概念模型类,二者配合使用。ResourceHandlerRegistry用于保存服务静态资源图片,css文件或者其他文件的资源处理器(resource handler)的注册信息,而ResourceHandlerRegistration就表示这样的"注册信息",它还包含了对...
springboot中配置addResourceHandler和addResourceLocations,可以使得可以从磁盘中读取图片、视频、音频等
例如我们要读取该文件夹下的文件
WebMvcConfig的代码
//以windows系统下为例
//对静态资源的配置
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
// addResourceHandler("/smallapple/**"),
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/imctemp-rainy/**").addResourceLocations("file:D:/E/");
设置静态资源路径
2. 表单 前端 页面
<input type="file" name="file" id="file">
<p id="
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.1.1.RELEASE</version>
</dependency>
二、配置WebMvcConfigurer,设置url访问静态资源映射
该项目由springboot搭建,提供漫画更新、查找等功能。可与的漫画爬虫页搭配使用
spring、springmvc、mybatis、springboot
漫画实体存放说明
该项目存放的漫画都在本人PC上,通过配置,让漫画地址映射到本机文件夹特定目录。由此,可直接通过http访问本机漫画。
以下是映射的实现代码:
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Value("${cbs.imagesPath}")
private String imagesPath;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
顺便有个svg文件动态缩放功能,用到了jquery.svg.pan.zoom.js
具体操作左键双击可以放大,滚轮也可以操作
参考 https://github.com/jiunong/jquery-svg-pan-zoom
访问地址:localhost:port(9999)/i/{svgfilename}
/**WebResourceConfig.java 配置svg文件位置*/
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/svg/**").addResourceLocations("fil
场景:部署的
Springboot项目,打成jar包,需要通过url直接访问jar外部路径的资源,本人的
Springboot为2.1.11.RELEASE。
一、配置Web
MvcConfigurer,设置url访问静态资源映射
@Configuration
public class Web
MvcConfig implements Web
MvcConfigurer {
使用
springboot配置映射静态资源目录后,英文和数字可以正常进行访问,但是中文就提示404
@Override
public void add
ResourceHandlers(
ResourceHandlerRegistry registry) {
registry.add
ResourceHandler("/file/video/**").add
ResourceLocations(props.getVideoFolder());
二 解决办法
原文传送门,有分析过程
1. xml配置<mvc:resources location="/WEB-INF/excel/" mapping="/download/excel/**" />不赘述2.资源拦截处理package com.xxx.calculator.webapp.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;...
拦截器类 需要两个配合使用这里只有一个
@Configuration
public class ServletContextConfig extends WebMvcConfigurerAdapter {
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
registry.addResourceHandler("/templates/**").addResourceLocations("classpath:/templates/");
super.addResourceHandlers(registry);
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new HandlerMyInterceptorAdapter()).addPathPatterns("/**")
.excludePathPatterns("/")
// .excludePathPatterns("/expressions/getExpressionsList")
.excludePathPatterns("/loginInfo/getCordByIsPhone")
.excludePathPatterns("/loginInfo/login11") //token失效跳轉
.excludePathPatterns("/loginInfo/insertLoginInfo") //注册
.excludePathPatterns("/loginInfo/login") //登录
.excludePathPatterns("/upload") //上传文件
.excludePathPatterns("/uploadListen") //上传文件
.excludePathPatterns("/admin/user/goLogin") //后台跳转登录
.excludePathPatterns("/admin/user/login") //后台登录
.excludePathPatterns("/loginInfo/getLoginInfo") //忘记密码
.excludePathPatterns("/loginInfo/getCord") //短信验证码
.excludePathPatterns("/loginInfo/getIsLoginInfo") //判断验证码&&登录
.excludePathPatterns("/loginInfo/getIsLoginInfo1") //判断验证码
.excludePathPatterns("/loginInfo/setPassWord") //设置密码
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
@Component
public class HandlerMyInterceptorAdapter implements HandlerInterceptor {
@Autowired
private HeartbeatServiceImpl heartbeatService;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
String url = request.getRequestURI();
if (url.contains("admin")) {
User user = (User) request.getSession().getAttribute("user");
try {
if (user.equals(null)) {
response.sendRedirect(serverConfig.SERVER + "admin/user/goLogin");
return false;
} else {
return true;
}catch (Exception e){
response.sendRedirect(serverConfig.SERVER + "admin/user/goLogin");
return false;
}else {
String token = request.getHeader("token");
if (token != null) {
Jedis jedis = new Jedis(com.sevenSteps.util.RedisConfig.HOST, RedisConfig.PORT);
String s = jedis.get(token);
if(token.equals(s)) {
heartbeatService = SpringUtil.getBean(HeartbeatServiceImpl.class);
return heartbeatService.setOutDate(token);
}else {
response.sendRedirect(serverConfig.SERVER + "loginInfo/login11");
return true;
}else {
response.sendRedirect(serverConfig.SERVER + "loginInfo/login11");
return true;
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object o, ModelAndView modelAndView) throws Exception {
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**")
.addResourceLocations("classpath:/static/");
* 模板资源解释器
* @return
@Bean
@Config
<mvc:annotation-driven />是Spring MVC框架中的一个配置标签,用于启用注解驱动的控制器和处理器映射器。它会自动注册一些默认的处理器,如RequestMappingHandlerMapping和RequestMappingHandlerAdapter,以便支持使用注解来处理请求和响应。同时,它还会自动注册一些默认的消息转换器,如StringHttpMessageConverter和MappingJackson2HttpMessageConverter,以便支持请求和响应的数据格式转换。使用<mvc:annotation-driven />标签可以简化Spring MVC的配置,提高开发效率。