search
HomeJavajavaTutorialDetailed explanation of static resource loading examples in java

Detailed explanation of static resource loading examples in java

May 10, 2017 am 10:28 AM
bootspringStatic resources

This article mainly introduces the static resource loading processing method in spring boot. Friends who need it can refer to it

1.spring boot default resource processing

Spring Boot provides us with static resource processing by default, using various properties configured in WebMvcAutoConfiguration.

The default path for spring boot to load files is:

/META-INF/resources/
/resources/
/static/
/public/

Under these directories, of course we can also see the Java code from the spring boot source code:

private static final String[] CLASSPATH_RESOURCE_LOCATIONS = { "classpath:/META-INF/resources/", "classpath:/resources/",  "classpath:/static/", "classpath:/public/" };

The above are all mapping paths of static resources, PriorityThe order is :META-INF/resources > resources > static > public

All local static resources are configured under the classpath, not under the webapp.

If the Sping MVC provided by Spring Boot does not meet the requirements, you can achieve fully controlled MVC configuration through a configuration class (a class annotated with @Configuration) plus the @EnableWebMvc annotation.

Of course, under normal circumstances, Spring Boot's automatic configuration meets most of our needs. When you need to retain the convenience provided by Spring Boot and add your own additional configuration, you can define a configuration class and inherit WebMvcConfigurerAdapter without using the @EnableWebMvc annotation.

If @EnableWebMvc is used, it will automatically cover the official /static, /public, META-INF/resources, /resources and other directories for storing static resources.

2. Custom resource mapping

Here we mention the WebMvcConfigurerAdapter class. Overriding the methods in this class allows us to add For additional configurations, here we will introduce a few commonly used ones.

Custom resource mapping addResourceHandlers

For example, if we want to customize the static resource mapping directory, we only need to rewrite the addResourceHandlers method.

@Configuration
public class SimpleWebAppConfigurer extends WebMvcConfigurerAdapter {
  @Override
  public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/myresource/**").addResourceLocations("classpath:/myresource/");
    super.addResourceHandlers(registry);
  }
}

Add the mapping path through addResourceHandler, and then specify the path through addResourceLocations.

If we change /myresource/* to /* which is the same as the default, the system configuration will be overwritten. You can use addResourceLocations multiple times to add directories. The priority added first is higher than the one added later.

3. Use external resources

#If we want to specify an absolute path to the folder (such as H:/images/), then only You need to specify it using addResourceLocations.

// 可以直接使用addResourceLocations 指定磁盘绝对路径,同样可以配置多个位置,注意路径写法需要加上file:
registry.addResourceHandler("/myimgs/**").addResourceLocations("file:H:/myimgs/");

Configure through configuration file. The above is to use code to define the mapping of static resources. In fact, Spring Boot also provides us with the configuration that can be directly configured in application.properties (or .yml) Methods.

The configuration method is as follows:

# 默认值为 /**
spring.mvc.static-path-pattern=classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/
spring.resources.static-locations=这里设置要指向的路径,多个使用英文逗号隔开

Use spring.resources.static-locations to redefine the path pointed by pattern, supporting classpath: and file: (already explained above)

Note that only one spring.mvc.static-path-pattern can be defined, and multiple comma-separated methods are currently not supported.

【Related recommendations】

1. Free Java video tutorial

2. Comprehensive analysis of Java annotations

3. Alibaba Java Development Manual

The above is the detailed content of Detailed explanation of static resource loading examples in java. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Explain how the JVM acts as an intermediary between the Java code and the underlying operating system.Explain how the JVM acts as an intermediary between the Java code and the underlying operating system.Apr 29, 2025 am 12:23 AM

JVM works by converting Java code into machine code and managing resources. 1) Class loading: Load the .class file into memory. 2) Runtime data area: manage memory area. 3) Execution engine: interpret or compile execution bytecode. 4) Local method interface: interact with the operating system through JNI.

Explain the role of the Java Virtual Machine (JVM) in Java's platform independence.Explain the role of the Java Virtual Machine (JVM) in Java's platform independence.Apr 29, 2025 am 12:21 AM

JVM enables Java to run across platforms. 1) JVM loads, validates and executes bytecode. 2) JVM's work includes class loading, bytecode verification, interpretation execution and memory management. 3) JVM supports advanced features such as dynamic class loading and reflection.

What steps would you take to ensure a Java application runs correctly on different operating systems?What steps would you take to ensure a Java application runs correctly on different operating systems?Apr 29, 2025 am 12:11 AM

Java applications can run on different operating systems through the following steps: 1) Use File or Paths class to process file paths; 2) Set and obtain environment variables through System.getenv(); 3) Use Maven or Gradle to manage dependencies and test. Java's cross-platform capabilities rely on the JVM's abstraction layer, but still require manual handling of certain operating system-specific features.

Are there any areas where Java requires platform-specific configuration or tuning?Are there any areas where Java requires platform-specific configuration or tuning?Apr 29, 2025 am 12:11 AM

Java requires specific configuration and tuning on different platforms. 1) Adjust JVM parameters, such as -Xms and -Xmx to set the heap size. 2) Choose the appropriate garbage collection strategy, such as ParallelGC or G1GC. 3) Configure the Native library to adapt to different platforms. These measures can enable Java applications to perform best in various environments.

What are some tools or libraries that can help you address platform-specific challenges in Java development?What are some tools or libraries that can help you address platform-specific challenges in Java development?Apr 29, 2025 am 12:01 AM

OSGi,ApacheCommonsLang,JNA,andJVMoptionsareeffectiveforhandlingplatform-specificchallengesinJava.1)OSGimanagesdependenciesandisolatescomponents.2)ApacheCommonsLangprovidesutilityfunctions.3)JNAallowscallingnativecode.4)JVMoptionstweakapplicationbehav

How does the JVM manage garbage collection across different platforms?How does the JVM manage garbage collection across different platforms?Apr 28, 2025 am 12:23 AM

JVMmanagesgarbagecollectionacrossplatformseffectivelybyusingagenerationalapproachandadaptingtoOSandhardwaredifferences.ItemploysvariouscollectorslikeSerial,Parallel,CMS,andG1,eachsuitedfordifferentscenarios.Performancecanbetunedwithflagslike-XX:NewRa

Why can Java code run on different operating systems without modification?Why can Java code run on different operating systems without modification?Apr 28, 2025 am 12:14 AM

Java code can run on different operating systems without modification, because Java's "write once, run everywhere" philosophy is implemented by Java virtual machine (JVM). As the intermediary between the compiled Java bytecode and the operating system, the JVM translates the bytecode into specific machine instructions to ensure that the program can run independently on any platform with JVM installed.

Describe the process of compiling and executing a Java program, highlighting platform independence.Describe the process of compiling and executing a Java program, highlighting platform independence.Apr 28, 2025 am 12:08 AM

The compilation and execution of Java programs achieve platform independence through bytecode and JVM. 1) Write Java source code and compile it into bytecode. 2) Use JVM to execute bytecode on any platform to ensure the code runs across platforms.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment