springmvc静态资源配置

  <servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <async-supported>false</async-supported>
  </servlet>

  <servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

在javaweb项目中配置了DispatcherServlet的情况下,如果不进行额外配置的话,几乎所有的请求都会走这个servlet来处理,默认静态资源按路径是访问不到的会报404错误,下面讲一讲如何配置才能访问到静态资源,本文将介绍三种方法

1. 在java配置文件中配置DefaultServletHttpRequestHandler来进行处理 

@Configuration
@EnableWebMvc
public class MyMvcConfigurer implements WebMvcConfigurer {

  @Override
  public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
    // tomcat默认处理静态资源的servlet名称为default,不指定也可以DefaultServletHttpRequestHandler.setServletContext会自动获取
//    configurer.enable("default");
    configurer.enable();
  }
}

上述配置完成后org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport#defaultServletHandlerMapping 方法会生成一个类名为SimpleUrlHandlerMapping的bean,当其他handlerMapping无法处理请求时会接着调用SimpleUrlHandlerMapping对象进行处理

org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport#defaultServletHandlerMapping
/**
 * Return a handler mapping ordered at Integer.MAX_VALUE with a mapped
 * default servlet handler. To configure "default" Servlet handling,
 * override {@link #configureDefaultServletHandling}.
 */
@Bean
public HandlerMapping defaultServletHandlerMapping() {
  Assert.state(this.servletContext != null, "No ServletContext set");
  DefaultServletHandlerConfigurer configurer = new DefaultServletHandlerConfigurer(this.servletContext);
  configureDefaultServletHandling(configurer);

  HandlerMapping handlerMapping = configurer.buildHandlerMapping();
  return (handlerMapping != null ? handlerMapping : new EmptyHandlerMapping());
}


org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer#buildHandlerMapping
@Nullable
protected SimpleUrlHandlerMapping buildHandlerMapping() {
  if (this.handler == null) {
    return null;
  }

  SimpleUrlHandlerMapping handlerMapping = new SimpleUrlHandlerMapping();
  handlerMapping.setUrlMap(Collections.singletonMap("/**", this.handler));
  handlerMapping.setOrder(Integer.MAX_VALUE);
  return handlerMapping;
}

SimpleUrlHandlerMapping中有一个urlMap属性,key为请求路径匹配模式串,'/**'能匹配所有的路径, value为handler匹配完成后会调用handler处理请求 

下面这个方法主要用来匹配获取handler

org.springframework.web.servlet.handler.AbstractUrlHandlerMapping#getHandlerInternal

 	@Override
	@Nullable
	protected Object getHandlerInternal(HttpServletRequest request) throws Exception {
		// 请求静态资源 path=/zxq/static/login.png
		// 处理完lookupPath=/static/login.png
		String lookupPath = getUrlPathHelper().getLookupPathForRequest(request);
		Object handler = lookupHandler(lookupPath, request);
		if (handler == null) {
			// We need to care for the default handler directly, since we need to
			// expose the PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE for it as well.
			Object rawHandler = null;
			if ("/".equals(lookupPath)) {
				rawHandler = getRootHandler();
			}
			if (rawHandler == null) {
				rawHandler = getDefaultHandler();
			}
			if (rawHandler != null) {
				// Bean name or resolved handler?
				if (rawHandler instanceof String) {
					String handlerName = (String) rawHandler;
					rawHandler = obtainApplicationContext().getBean(handlerName);
				}
				validateHandler(rawHandler, request);
				handler = buildPathExposingHandler(rawHandler, lookupPath, lookupPath, null);
			}
		}
		if (handler != null && logger.isDebugEnabled()) {
			logger.debug("Mapping ["   lookupPath   "] to "   handler);
		}
		else if (handler == null && logger.isTraceEnabled()) {
			logger.trace("No handler mapping found for ["   lookupPath   "]");
		}
		return handler;
	}

org.springframework.web.servlet.handler.AbstractUrlHandlerMapping#lookupHandler

 	/**
	 * Look up a handler instance for the given URL path.
	 * <p>Supports direct matches, e.g. a registered "/test" matches "/test",
	 * and various Ant-style pattern matches, e.g. a registered "/t*" matches
	 * both "/test" and "/team". For details, see the AntPathMatcher class.
	 * <p>Looks for the most exact pattern, where most exact is defined as
	 * the longest path pattern.
	 * @param urlPath the URL the bean is mapped to
	 * @param request current HTTP request (to expose the path within the mapping to)
	 * @return the associated handler instance, or {@code null} if not found
	 * @see #exposePathWithinMapping
	 * @see org.springframework.util.AntPathMatcher
	 */
	@Nullable
	protected Object lookupHandler(String urlPath, HttpServletRequest request) throws Exception {
		// Direct match?
		// 精确匹配,是否有符合的handler
		// urlPath = /static/login.png
		Object handler = this.handlerMap.get(urlPath);
		if (handler != null) {
			// Bean name or resolved handler?
			if (handler instanceof String) {
				String handlerName = (String) handler;
				handler = obtainApplicationContext().getBean(handlerName);
			}
			validateHandler(handler, request);
			return buildPathExposingHandler(handler, urlPath, urlPath, null);
		}

		// Pattern match?
		// 路径匹配
		List<String> matchingPatterns = new ArrayList<>();
		for (String registeredPattern : this.handlerMap.keySet()) {
			if (getPathMatcher().match(registeredPattern, urlPath)) {
				matchingPatterns.add(registeredPattern);
			}
			else if (useTrailingSlashMatch()) {
				if (!registeredPattern.endsWith("/") && getPathMatcher().match(registeredPattern   "/", urlPath)) {
					matchingPatterns.add(registeredPattern   "/");
				}
			}
		}

		String bestMatch = null;
		Comparator<String> patternComparator = getPathMatcher().getPatternComparator(urlPath);
		if (!matchingPatterns.isEmpty()) {
			matchingPatterns.sort(patternComparator);
			if (logger.isDebugEnabled()) {
				logger.debug("Matching patterns for request ["   urlPath   "] are "   matchingPatterns);
			}
			bestMatch = matchingPatterns.get(0);
		}
		// bestMatch = /static/**
		if (bestMatch != null) {
			handler = this.handlerMap.get(bestMatch);
			if (handler == null) {
				if (bestMatch.endsWith("/")) {
					handler = this.handlerMap.get(bestMatch.substring(0, bestMatch.length() - 1));
				}
				if (handler == null) {
					throw new IllegalStateException(
							"Could not find handler for best pattern match ["   bestMatch   "]");
				}
			}
			// Bean name or resolved handler?
			if (handler instanceof String) {
				String handlerName = (String) handler;
				handler = obtainApplicationContext().getBean(handlerName);
			}
			validateHandler(handler, request);
			// login.png
			String pathWithinMapping = getPathMatcher().extractPathWithinPattern(bestMatch, urlPath);

			// There might be multiple 'best patterns', let's make sure we have the correct URI template variables
			// for all of them
			Map<String, String> uriTemplateVariables = new LinkedHashMap<>();
			for (String matchingPattern : matchingPatterns) {
				if (patternComparator.compare(bestMatch, matchingPattern) == 0) {
					Map<String, String> vars = getPathMatcher().extractUriTemplateVariables(matchingPattern, urlPath);
					Map<String, String> decodedVars = getUrlPathHelper().decodePathVariables(request, vars);
					uriTemplateVariables.putAll(decodedVars);
				}
			}
			if (logger.isDebugEnabled()) {
				logger.debug("URI Template variables for request ["   urlPath   "] are "   uriTemplateVariables);
			}
			// /static/**   login.png
			return buildPathExposingHandler(handler, bestMatch, pathWithinMapping, uriTemplateVariables);
		}

		// No handler found...
		return null;
	}

接着调用DefaultServletHttpRequestHandler的handleRequest方法处理请求,逻辑比较简单,获取请求转发器进行请求转发交给tomcat默认的servlet来进行处理 

	@Override
	public void handleRequest(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		Assert.state(this.servletContext != null, "No ServletContext set");
		RequestDispatcher rd = this.servletContext.getNamedDispatcher(this.defaultServletName);
		if (rd == null) {
			throw new IllegalStateException("A RequestDispatcher could not be located for the default servlet '"  
					this.defaultServletName   "'");
		}
		rd.forward(request, response);
	}

2. 在java配置文件中配置ResourceHttpRequestHandler来进行处理 

@Configuration
@EnableWebMvc
public class MyMvcConfigurer implements WebMvcConfigurer {

  @Override
  public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/static/**").addResourceLocations("/static/");
  }
}

和第一种配置几乎一样,其实只是换了一个handler类型来处理请求罢了

上述配置完成后org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport#resourceHandlerMapping 方法会生成一个类名为SimpleUrlHandlerMapping的bean,当其他handlerMapping无法处理请求时会接着调用SimpleUrlHandlerMapping对象进行处理

ResourceHttpRequestHandler比DefaultServletHttpRequestHandler的构建稍微复杂一点

org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport#resourceHandlerMapping
/**
 * Return a handler mapping ordered at Integer.MAX_VALUE-1 with mapped
 * resource handlers. To configure resource handling, override
 * {@link #addResourceHandlers}.
 */
@Bean
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) {
    handlerMapping.setPathMatcher(mvcPathMatcher());
    handlerMapping.setUrlPathHelper(mvcUrlPathHelper());
    handlerMapping.setInterceptors(getInterceptors());
    handlerMapping.setCorsConfigurations(getCorsConfigurations());
  }
  else {
    handlerMapping = new EmptyHandlerMapping();
  }
  return handlerMapping;
}


org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry#getHandlerMapping
/**
 * Return a handler mapping with the mapped resource handlers; or {@code 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(order);
  handlerMapping.setUrlMap(urlMap);
  return handlerMapping;
}

 之后也是调用SimpleUrlHandlerMapping相同的逻辑先根据请求路径匹配找到对应处理的handler,这里对应的是ResourceHttpRequestHandler之后调用handleRequest方法,原理是先根据请求的路径找到对应的资源文件,再获取资源文件的输入流写入到response响应中,源码如下:

org.springframework.web.servlet.resource.ResourceHttpRequestHandler#handleRequest

 /**
 * Processes a resource request.
 * <p>Checks for the existence of the requested resource in the configured list of locations.
 * If the resource does not exist, a {@code 404} response will be returned to the client.
 * If the resource exists, the request will be checked for the presence of the
 * {@code Last-Modified} header, and its value will be compared against the last-modified
 * timestamp of the given resource, returning a {@code 304} status code if the
 * {@code Last-Modified} value  is greater. If the resource is newer than the
 * {@code Last-Modified} value, or the header is not present, the content resource
 * of the resource will be written to the response with caching headers
 * set to expire one year in the future.
 */
@Override
public void handleRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {

  // For very general mappings (e.g. "/") we need to check 404 first
  // 根据请求的文件路径找到对应的资源文件
  Resource resource = getResource(request);
  if (resource == null) {
    logger.trace("No matching resource found - returning 404");
    response.sendError(HttpServletResponse.SC_NOT_FOUND);
    return;
  }

  if (HttpMethod.OPTIONS.matches(request.getMethod())) {
    response.setHeader("Allow", getAllowHeader());
    return;
  }

  // Supported methods and required session
  // 校验支持的方法GET和HEAD 以及验证session是否必须
  checkRequest(request);

  // Header phase
  if (new ServletWebRequest(request, response).checkNotModified(resource.lastModified())) {
    logger.trace("Resource not modified - returning 304");
    return;
  }

  // Apply cache settings, if any
  // 可以根据设置的秒数设置缓存时间 cache-control:max-age=xxx
  prepareResponse(response);

  // Check the media type for the resource
  // 根据文件后缀去寻找 png -> image/png
  MediaType mediaType = getMediaType(request, resource);
  if (mediaType != null) {
    if (logger.isTraceEnabled()) {
      logger.trace("Determined media type '"   mediaType   "' for "   resource);
    }
  }
  else {
    if (logger.isTraceEnabled()) {
      logger.trace("No media type found for "   resource   " - not sending a content-type header");
    }
  }

  // Content phase
  if (METHOD_HEAD.equals(request.getMethod())) {
    setHeaders(response, resource, mediaType);
    logger.trace("HEAD request - skipping content");
    return;
  }

  ServletServerHttpResponse outputMessage = new ServletServerHttpResponse(response);
  if (request.getHeader(HttpHeaders.RANGE) == null) {
    Assert.state(this.resourceHttpMessageConverter != null, "Not initialized");
    // 设置content-type、content-length等响应头
    setHeaders(response, resource, mediaType);
    // 将文件流写入到response响应中
    this.resourceHttpMessageConverter.write(resource, mediaType, outputMessage);
  }
  else {
    Assert.state(this.resourceRegionHttpMessageConverter != null, "Not initialized");
    response.setHeader(HttpHeaders.ACCEPT_RANGES, "bytes");
    ServletServerHttpRequest inputMessage = new ServletServerHttpRequest(request);
    try {
      List<HttpRange> httpRanges = inputMessage.getHeaders().getRange();
      response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
      this.resourceRegionHttpMessageConverter.write(
          HttpRange.toResourceRegions(httpRanges, resource), mediaType, outputMessage);
    }
    catch (IllegalArgumentException ex) {
      response.setHeader("Content-Range", "bytes */"   resource.contentLength());
      response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
    }
  }
}

3.  web.xml配置servlet映射 

原理可以参考上一篇文章 

  <servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>/static/*</url-pattern>
  </servlet-mapping>

将带有/static/xxx 路径的请求直接交给tomcat默认的servlet去进行处理 

最后

完成上述的一种配置后就能访问到我们的静态资源了,请求路径http://localhost:8082/zxq/static/login.png

补充

若配置了拦截器且使用第二种方法,拦截器也会对静态资源进行拦截,若不需要拦截还需要进行额外的配置去除比较麻烦

第一种方法用dispatcherServlet拦截所有的请求再将请求交给tomcat默认的servlet处理,性能上有所消耗,拦截器不过滤

第二种方法拦截器会进行过滤若需要过滤的路径较多配置麻烦 

第三种方法直接用tomcat默认的servlet进行处理,但静态资源路径有多个时配置也比较麻烦 

综上所述,根据自己项目的情况选择哪一种方法~ 

@Configuration
@EnableWebMvc
public class MyMvcConfigurer implements WebMvcConfigurer {

  @Resource
  private CustomInterceptor customInterceptor;

  @Override
  public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(customInterceptor)
        .addPathPatterns("/**")
        .excludePathPatterns("/static/**");
  }

//  @Override
//  public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
//    // tomcat默认处理静态资源的servlet名称为default,不指定也可以DefaultServletHttpRequestHandler.setServletContext会自动获取
////    configurer.enable("default");
//    configurer.enable();
//  }

  @Override
  public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/static/**").addResourceLocations("/static/");
  }
}

以上就是SpringMVC静态资源配置过程详解的详细内容,更多关于SpringMVC静态资源配置的资料请关注Devmax其它相关文章!

SpringMVC静态资源配置过程详解的更多相关文章

  1. JSP中springmvc配置validator的注意事项

    这篇文章主要介绍了JSP中springmvc配置validator的注意事项的相关资料,并说明springmvc中spring-servlet.xml、applicationContext.xml的区别需要的朋友可以参考下

  2. SpringMVC拦截器和异常处理器使用示例超详细讲解

    拦截器(Interceptor)是一种动态拦截方法调用的机制,在SpringMVC中动态拦截控制器方法的执行。本文将详细讲讲SpringMVC中拦截器参数及拦截器链配置,感兴趣的可以尝试一下

  3. JSP开发入门(五)--JSP其他相关资源

    JSP其他相关资源:ServletsandJavaServerPages(JSP)1.0:ATutorialhttp://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/JavaServerPagesTM:ADeveloper'sPerspectivehttp://developer.java.sun.com/developer/technicalArtic

  4. Yii2语言国际化自动配置详解

    这篇文章主要介绍了Yii2语言国际化自动配置详解,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

  5. SpringMVC数据页响应ModelAndView实现页面跳转

    本文主要介绍了SpringMVC数据页响应ModelAndView实现页面跳转,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

  6. SpringMVC静态资源配置过程详解

    在javaweb项目中配置了DispatcherServlet的情况下,如果不进行额外配置的话,几乎所有的请求都会走这个servlet来处理,默认静态资源按路径是访问不到的会报404错误,下面就来讲一讲如何配置才能访问到静态资源吧

  7. 关于@RequestLine的使用及配置

    这篇文章主要介绍了关于@RequestLine的使用及配置方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

  8. SpringBoot配置拦截器实现过程详解

    在系统中经常需要在处理用户请求之前和之后执行一些行为,例如检测用户的权限,或者将请求的信息记录到日志中,即平时所说的"权限检测"及"日志记录",下面这篇文章主要给大家介绍了关于在SpringBoot项目中整合拦截器的相关资料,需要的朋友可以参考下

  9. SpringBoot浅析安全管理之Spring Security配置

    安全管理是软件系统必不可少的的功能。根据经典的“墨菲定律”——凡是可能,总会发生。如果系统存在安全隐患,最终必然会出现问题,这篇文章主要介绍了SpringBoot安全管理Spring Security基本配置

  10. Vue3 源码解读静态提升详解

    这篇文章主要为大家介绍了Vue3源码解读静态提升示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

随机推荐

  1. Java利用POI实现导入导出Excel表格

    这篇文章主要为大家详细介绍了Java利用POI实现导入导出Excel表格,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

  2. Mybatis分页插件PageHelper手写实现示例

    这篇文章主要为大家介绍了Mybatis分页插件PageHelper手写实现示例,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

  3. (jsp/html)网页上嵌入播放器(常用播放器代码整理)

    网页上嵌入播放器,只要在HTML上添加以上代码就OK了,下面整理了一些常用的播放器代码,总有一款适合你,感兴趣的朋友可以参考下哈,希望对你有所帮助

  4. Java 阻塞队列BlockingQueue详解

    本文详细介绍了BlockingQueue家庭中的所有成员,包括他们各自的功能以及常见使用场景,通过实例代码介绍了Java 阻塞队列BlockingQueue的相关知识,需要的朋友可以参考下

  5. Java异常Exception详细讲解

    异常就是不正常,比如当我们身体出现了异常我们会根据身体情况选择喝开水、吃药、看病、等 异常处理方法。 java异常处理机制是我们java语言使用异常处理机制为程序提供了错误处理的能力,程序出现的错误,程序可以安全的退出,以保证程序正常的运行等

  6. Java Bean 作用域及它的几种类型介绍

    这篇文章主要介绍了Java Bean作用域及它的几种类型介绍,Spring框架作为一个管理Bean的IoC容器,那么Bean自然是Spring中的重要资源了,那Bean的作用域又是什么,接下来我们一起进入文章详细学习吧

  7. 面试突击之跨域问题的解决方案详解

    跨域问题本质是浏览器的一种保护机制,它的初衷是为了保证用户的安全,防止恶意网站窃取数据。那怎么解决这个问题呢?接下来我们一起来看

  8. Mybatis-Plus接口BaseMapper与Services使用详解

    这篇文章主要为大家介绍了Mybatis-Plus接口BaseMapper与Services使用详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

  9. mybatis-plus雪花算法增强idworker的实现

    今天聊聊在mybatis-plus中引入分布式ID生成框架idworker,进一步增强实现生成分布式唯一ID,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

  10. Spring JdbcTemplate执行数据库操作详解

    JdbcTemplate是Spring框架自带的对JDBC操作的封装,目的是提供统一的模板方法使对数据库的操作更加方便、友好,效率也不错,这篇文章主要介绍了Spring JdbcTemplate执行数据库操作,需要的朋友可以参考下

返回
顶部