Konfigurácia statického súboru Spring Boot A zväzok
Spring Boot Static File Configuration Volume
Povedzte slová vpredu:
-
Vytvorte aplikáciu SpringBoot a vyberte modul, ktorý potrebujeme
-
SpringBoot nakonfiguroval tieto scenáre predvolene a na spustenie je potrebné zadať iba malý počet konfigurácií.
-
Napíšte svoj vlastný obchodný kód
Pretože Spring Boot používa špecifikáciu „konvencie nad konfiguráciou“, je tiež veľmi jednoduchá pri použití statických prostriedkov.
SpringBoot je v podstate mikroslužba. Začína sa to v JAR, ale niekedy je nevyhnutný prístup k statickým zdrojom, napríklad prístup k zdrojom, ako sú obrázky, js a css.
1. statická cesta konfigurácie webjars
Je ľahké pochopiť, nie je to príliš praktické.
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)) } } } }
Analýza kódu: Všetko /webjars/**
, obe možnosti classpath:/META-INF/resources/webjars/
vyhľadanie zdrojov Webjars: Predstavuje statické prostriedky vo forme balíkov jar. Závislá oficiálna webová stránka poskytovaná webjars
<dependency> <groupId>org.webjarsgroupId> <artifactId>jqueryartifactId> <version>1.12.4version> dependency>
Spustite službu, otestujte prístup k statickej adrese http://127.0.0.1:8001/hp/webjars/jquery/1.12.4/jquery.js
2. Predvolená cesta statického prostriedku
@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 } }
Výňatková časť zdrojového kódu, aby sme zväčšili dĺžku, môžeme vidieť z vyššie uvedeného kódu, poskytneme niekoľko predvolených konfiguračných metód
classpath:/static classpath:/public classpath:/resources classpath:/META-INF/resources Remarks: '/'=> the root path of the current project
Vytvoríme nové verejné, zdrojové, statické, META-INF a ďalšie adresáre v adresári src / main / resources a vložíme ich do 1.jpg 2.jpg 3.jpg 4.jpg 5.jpg Päť obrázkov.
** Poznámka: ** je potrebné vylúčiť formu webjars, odstrániť kód v pom.xml, výsledky výsledkov testu sú nasledovné
3. Pridajte cestu statického zdroja
sme na spring.resources.static-locations
Pripojiť konfiguráciu neskôr 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. Vlastné statické mapovanie zdrojov
Pri skutočnom vývoji možno budeme musieť prispôsobiť prístup k statickým prostriedkom a cestu nahrávania, najmä nahrávanie súborov, nie je možné nahrať spustenú službu JAR, potom môžete implementovať vlastné mapovanie cesty dedením WebMvcConfigurerAdapter.
Konfigurácia súboru Application.properties:
# Picture audio upload path configuration (win system changes the local path by itself) web.upload.path=D:/upload/attr/
Konfigurácia spustenia 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. Nastavte uvítacie rozhranie
Stále od zdroja na vyriešenie tohto problému
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 Priame nastavenie statickej predvolenej stránky
Uvítacia stránka, všetky stránky index.html v priečinku statických prostriedkov sú mapované znakom „/ **“
5.2 Spôsoby zvýšenia regulátora
-
Pridaná podpora pre šablónový modul
<dependency> <groupId>org.springframework.bootgroupId> <artifactId>spring-boot-starter-thymeleafartifactId> dependency>
-
Nakonfigurujte hlavný súbor application.properties
server.port=8001 server.servlet.context-path=/hp spring.mvc.view.prefix=classpath:/templates/
Nenastavil som názov prípony
-
Nastaviť trasu
@Controller public class IndexController { @GetMapping({'/','/index'}) public String index(){ return 'default' } }
-
prístup
http://127.0.0.1:8001/hp/
5.3 Nastavenie predvolenej skokovej stránky Zobraziť
-
Pridaná podpora pre šablónový modul
<dependency> <groupId>org.springframework.bootgroupId> <artifactId>spring-boot-starter-thymeleafartifactId> dependency>
-
Nakonfigurujte hlavný súbor application.properties
server.port=8001 server.servlet.context-path=/hp spring.mvc.view.prefix=classpath:/templates/
Nenastavil som názov prípony
-
Štartovací súbor je upravený nasledovne
@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. Nastavenia favicon
@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 štandardne spúšťa Favicon a poskytuje predvolený Favicon. Ak chcete zavrieť Favicon, stačí ho pridať do application.properties.
spring.mvc.favicon.enabled=false
Ak chcete zmeniť Favicon, jednoducho vložte svoj vlastný Favicon.ico (názov súboru sa nedá zmeniť), vložte ho do koreňového adresára classpath, classpath META_INF / resources /, classpath resources /, classpath static / alebo classpath public / pod.
5. Príloha
A.WebMvcConfigurerAdapter je zastaraný
Pri konfigurácii WebMvcConfigurerAdapter v Springboot som zistil, že táto trieda je zastaraná. Pozrel som sa teda na zdrojový kód a zistil som, že úradník v spring5 zastaral WebMvcConfigurerAdapter, pretože springboot2.0 používa spring5, takže bude pôsobiť zastarane.
WebMvcConfigurerAdapter je zastaraný a v novej verzii bol zastaraný. Nasledujú najbežnejšie prepisovacie rozhrania:
/** 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)
Možnosť 1: Priama implementácia WebMvcConfigurer
@Configuration public class WebMvcConfg implements WebMvcConfigurer { @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController('/index').setViewName('index') } }
Scenár 2: Priamo dedte WebMvcConfigurationSupport
@Configuration public class WebMvcConfg extends WebMvcConfigurationSupport { @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController('/index').setViewName('index') } }
V skutočnosti je WebMvcConfigurerAdapter implementáciou rozhrania WebMvcConfigurer, takže rozhranie WebMvcConfigurer je možné priamo implementovať WebMvcConfigurationSupport a WebMvcConfigurerAdapter, rozhranie WebMvcConfigurer v rovnakom adresári WebMvcConfigurationSupport obsahuje WebMvcConfigurer, pokiaľ by mala WebConvporovať, mala by používať byť nahradením a rozšírením WebMvcConfigurerAdapter v novej verzii.
B. Informácie o načítaní problémov s adresárom
// 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/')