且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Spring-webmvc源码解析之PathResourceResolver

更新时间:2022-08-21 19:29:21

基于4.1.7.RELEASE

本类是resolver链的最后一个,所以不会对resolverchain做任何操作。

private boolean isResourceUnderLocation(Resource resource, Resource location) throws IOException {
   if (!resource.getClass().equals(location.getClass())) {
      return false;
   }
   String resourcePath;
   String locationPath;
   /*  此处对上面两个path进行判断赋值,为了简洁代码已删除 */
   if (!resourcePath.startsWith(locationPath)) {
      return false;
   }
   if (resourcePath.contains("%")) {
      // Use URLDecoder (vs UriUtils) to preserve potentially decoded UTF-8 chars...
      if (URLDecoder.decode(resourcePath, "UTF-8").contains("../")) {
         if (logger.isTraceEnabled()) {
            logger.trace("Resolved resource path contains \"../\" after decoding: " + resourcePath);
         }
         return false;
      }
   }
   return true;
}

关键代码是

if (!resourcePath.startsWith(locationPath)) {
      return false;
   }

这里判断资源路径是否与所给定的location匹配,如果不匹配则返回false导致checkResource方法返回false,从而使getResource方法返回null

protected Resource getResource(String resourcePath, Resource location) throws IOException {
   Resource resource = location.createRelative(resourcePath);
   if (resource.exists() && resource.isReadable()) {
      if (checkResource(resource, location)) {
         return resource;
      }
      else if (logger.isTraceEnabled()) {
         logger.trace(“somelog");
      }
   }
   return null;
}