SpringBoot静的ファイル構成ボリューム



Spring Boot Static File Configuration Volume



前の言葉を言う:

  • SpringBootアプリケーションを作成し、必要なモジュールを選択します



  • SpringBootはこれらのシナリオをデフォルトで構成しており、実行する構成ファイルで少数の構成を指定するだけで済みます。

  • 独自のビジネスコードを書く



Spring Bootは「設定より規約」仕様を使用しているため、静的リソースを使用する場合も非常に簡単です。

SpringBootは本質的にマイクロサービスです。 JARで始まりますが、image、js、cssなどのリソースへのアクセスなど、静的リソースへのアクセスが不可欠な場合があります。

1.webjars構成の静的パス

理解するのは簡単ですが、あまり実用的ではありません。



public class WebMvcAutoConfiguration { public void addResourceHandlers(ResourceHandlerRegistry registry) { if (!this.resourceProperties.isAddMappings()) { logger.debug('Default resource handling disabled') } else { Duration cachePeriod = this.resourceProperties.getCache().getPeriod() CacheControl cacheControl = this.resourceProperties.getCache().getCachecontrol().toHttpCacheControl() if (!registry.hasMappingForPattern('/webjars/**')) { this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{'/webjars/**'}).addResourceLocations(new String[]{'classpath:/META-INF/resources/webjars/'}).setCachePeriod(this.getSeconds(cachePeriod)).setCacheControl(cacheControl)) } String staticPathPattern = this.mvcProperties.getStaticPathPattern() if (!registry.hasMappingForPattern(staticPathPattern)) { this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{staticPathPattern}).addResourceLocations(getResourceLocations(this.resourceProperties.getStaticLocations())).setCachePeriod(this.getSeconds(cachePeriod)).setCacheControl(cacheControl)) } } } }

コード分​​析: すべて/webjars/**、両方行くclasspath:/META-INF/resources/webjars/リソースを探す Webjars:jarパッケージの形式で静的リソースを導入します。 webjarsが提供する依存する公式ウェブサイト

<dependency> <groupId>org.webjarsgroupId> <artifactId>jqueryartifactId> <version>1.12.4version> dependency>

サービスを開始し、静的アドレスへのアクセスをテストしますhttp://127.0.0.1:8001/hp/webjars/jquery/1.12.4/jquery.js

2.デフォルトの静的リソースパス

@ConfigurationProperties( prefix = 'spring.resources', ignoreUnknownFields = false ) public class ResourceProperties { private static final String[] CLASSPATH_RESOURCE_LOCATIONS = new String[]{'classpath:/META-INF/resources/', 'classpath:/resources/', 'classpath:/static/', 'classpath:/public/'} private String[] staticLocations private boolean addMappings private final ResourceProperties.Chain chain private final ResourceProperties.Cache cache public ResourceProperties() { this.staticLocations = CLASSPATH_RESOURCE_LOCATIONS this.addMappings = true this.chain = new ResourceProperties.Chain() this.cache = new ResourceProperties.Cache() } public String[] getStaticLocations() { return this.staticLocations } }

ソースコードの抜粋部分、長さを増やすために、上記のコードからわかるように、いくつかのデフォルトの構成方法を提供します

classpath:/static classpath:/public classpath:/resources classpath:/META-INF/resources Remarks: '/'=> the root path of the current project

src / main / resourcesディレクトリに新しいpublic、resources、static、META-INF、およびその他のディレクトリディレクトリを作成し、それらを1.jpg 2.jpg 3.jpg 4.jpg 5.jpg5枚の画像に配置します。

**注:** webjarの形式を除外し、pom.xmlのコードを削除する必要があります。テスト結果の結果は、次のとおりです。

3.静的リソースパスを追加します

spring.resources.static-locations後で構成を追加classpath:/os/

# Static file request matching method spring.mvc.static-path-pattern=/** # Modify the default statically addressed resource directory Multiple separated by commas spring.resources.static-locations = classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,classpath:/os/

4.カスタム静的リソースマッピング

実際の開発では、静的リソースアクセスとアップロードパス、特にファイルアップロードをカスタマイズする必要がある場合があります。実行中のJARサービスをアップロードすることはできません。その後、WebMvcConfigurerAdapterを継承してカスタムパスマッピングを実装できます。

Application.propertiesファイルの構成:

# Picture audio upload path configuration (win system changes the local path by itself) web.upload.path=D:/upload/attr/

Demo05BootApplication.javaスタートアップ構成:

package com.hanpang import org.slf4j.Logger import org.slf4j.LoggerFactory import org.springframework.beans.factory.annotation.Value import org.springframework.boot.SpringApplication import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry import org.springframework.web.servlet.config.annotation.WebMvcConfigurer @SpringBootApplication public class Demo05BootApplication implements WebMvcConfigurer { private final static Logger LOGGER = LoggerFactory.getLogger(Demo05BootApplication.class) @Value('${web.upload.path}') private String uploadPath @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler('/uploads/**').addResourceLocations( 'file:' + uploadPath) LOGGER.info('Custom Static Resource Directory, here for file mapping') } public static void main(String[] args) { SpringApplication.run(Demo05BootApplication.class, args) } }

5.ウェルカムインターフェイスを設定します

この問題を解決するためにまだソースから

public class WebMvcAutoConfiguration { private Optional<Resource> getWelcomePage() { String[] locations = getResourceLocations(this.resourceProperties.getStaticLocations()) return Arrays.stream(locations).map(this::getIndexHtml).filter(this::isReadable).findFirst() } private Resource getIndexHtml(String location) { return this.resourceLoader.getResource(location + 'index.html') } }

5.1静的デフォルトページを直接設定する

ウェルカムページ静的リソースフォルダーの下のすべてのindex.htmlページは「/ **」でマップされます

5.2コントローラーを増やす方法

  • テンプレートエンジンのサポートが追加されました

    <dependency> <groupId>org.springframework.bootgroupId> <artifactId>spring-boot-starter-thymeleafartifactId> dependency>
  • コアファイルapplication.propertiesを構成します

    server.port=8001 server.servlet.context-path=/hp spring.mvc.view.prefix=classpath:/templates/

    接尾辞名を設定しませんでした

  • ルートを設定する

    @Controller public class IndexController { @GetMapping({'/','/index'}) public String index(){ return 'default' } }
  • アクセスhttp://127.0.0.1:8001/hp/

5.3デフォルトのビュージャンプページの設定

  • テンプレートエンジンのサポートが追加されました

    <dependency> <groupId>org.springframework.bootgroupId> <artifactId>spring-boot-starter-thymeleafartifactId> dependency>
  • コアファイルapplication.propertiesを構成します

    server.port=8001 server.servlet.context-path=/hp spring.mvc.view.prefix=classpath:/templates/

    接尾辞名を設定しませんでした

  • スタートアップファイルは次のように変更されます

    @SpringBootApplication public class Demo05BootApplication implements WebMvcConfigurer { @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController('/').setViewName('default') registry.addViewController('/index1').setViewName('default') registry.setOrder(Ordered.HIGHEST_PRECEDENCE) } public static void main(String[] args) { SpringApplication.run(Demo05BootApplication.class, args) } }

6.ファビコン設定

@Configuration @ConditionalOnProperty( value = {'spring.mvc.favicon.enabled'}, matchIfMissing = true ) public static class FaviconConfiguration implements ResourceLoaderAware { private final ResourceProperties resourceProperties private ResourceLoader resourceLoader public FaviconConfiguration(ResourceProperties resourceProperties) { this.resourceProperties = resourceProperties } public void setResourceLoader(ResourceLoader resourceLoader) { this.resourceLoader = resourceLoader } @Bean public SimpleUrlHandlerMapping faviconHandlerMapping() { SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping() mapping.setOrder(-2147483647) mapping.setUrlMap(Collections.singletonMap('**/favicon.ico', this.faviconRequestHandler())) return mapping } @Bean public ResourceHttpRequestHandler faviconRequestHandler() { ResourceHttpRequestHandler requestHandler = new ResourceHttpRequestHandler() requestHandler.setLocations(this.resolveFaviconLocations()) return requestHandler } private List<Resource> resolveFaviconLocations() { String[] staticLocations = WebMvcAutoConfiguration.WebMvcAutoConfigurationAdapter.getResourceLocations(this.resourceProperties.getStaticLocations()) List<Resource> locations = new ArrayList(staticLocations.length + 1) Stream var10000 = Arrays.stream(staticLocations) ResourceLoader var10001 = this.resourceLoader var10001.getClass() var10000.map(var10001::getResource).forEach(locations::add) locations.add(new ClassPathResource('/')) return Collections.unmodifiableList(locations) } }

SpringBootはデフォルトでファビコンを起動し、デフォルトのファビコンを提供します。ファビコンを閉じたい場合は、application.propertiesに追加するだけです。

spring.mvc.favicon.enabled=false

ファビコンを変更する場合は、独自のFavicon.ico(ファイル名は変更できません)を配置し、クラスパスルートディレクトリ、クラスパスMETA_INF / resources /、クラスパスresources /、classpath static /またはclasspathpublic /に配置します。下。

5.付録

A.WebMvcConfigurerAdapterは古くなっています

SpringbootでWebMvcConfigurerAdapterを構成すると、このクラスが古くなっていることがわかりました。そこでソースコードを見ると、springboot2.0はspring5を使用しているため、spring5の公式はWebMvcConfigurerAdapterを非推奨にしていることがわかりました。

WebMvcConfigurerAdapterは廃止され、新しいバージョンでは非推奨になりました。以下は、より一般的な書き換えインターフェースです。

/** Resolve cross-domain issues **/ public void addCorsMappings(CorsRegistry registry) /** Add Interceptor **/ void addInterceptors(InterceptorRegistry registry) /** Configure view resolver here **/ void configureViewResolvers(ViewResolverRegistry registry) /** Some options for configuring content rulings **/ void configureContentNegotiation(ContentNegotiationConfigurer configurer) /** View Jump Controller **/ void addViewControllers(ViewControllerRegistry registry) /** Static Resource Processing **/ void addResourceHandlers(ResourceHandlerRegistry registry) /** Default Static Resource Processor **/ void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer)

オプション1:WebMvcConfigurerの直接実装

@Configuration public class WebMvcConfg implements WebMvcConfigurer { @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController('/index').setViewName('index') } }

シナリオ2:WebMvcConfigurationSupportを直接継承する

@Configuration public class WebMvcConfg extends WebMvcConfigurationSupport { @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController('/index').setViewName('index') } }

実際、WebMvcConfigurerAdapterはWebMvcConfigurerインターフェイスの実装であるため、WebMvcConfigurerインターフェイスを直接実装できます。WebMvcConfigurationSupportおよびWebMvcConfigurerAdapter、同じディレクトリ内のインターフェイスWebMvcConfigurer WebMvcConfigurationSupportにはメソッド内にWebMvcConfigurerが含まれます。このバージョンでは、WebMvcConfigurationSupportクラスのWebMvcConfigurationSupportを使用することをお勧めします。新しいバージョンのWebMvcConfigurerAdapterの代替および拡張になります。

B.ディレクトリの問題の読み込みについて

// You can use addResourceLocations to specify the absolute path of the disk. You can also configure multiple locations. Note that the path is written with the file: registry.addResourceHandler('/myimgs/**').addResourceLocations('file:H:/myimgs/') // The URL of fengjing.jpg in the root directory of myres is http://localhost:8080/fengjing.jpg (/** will override the default configuration of the system) registry.addResourceHandler('/**').addResourceLocations('classpath:/myres/').addResourceLocations('classpath:/static/')