In the first two chapters, we shared Spring boot's support for Restful, but the Restful interface usually only returns data. When doing web development, we often have a lot of static resources, such as html, pictures, css, etc. So how do you return static resources to the front end? Students who have done web development before should know that there will be a webapp directory under the web project we created before, and we can directly access it by placing static resources in this directory. However, Spring boot-based projects do not have this directory, so how should we deal with it?
1. The stupidest way
Let's first share the stupidest way, which is to return the static resources directly to the front-end through the stream. We create an html directory in the root directory of the resources of the maven project, and then we place the html file in this directory, and specify that any access path starts with /static/ is to access the static resources in the directory. The implementation is as follows:
@Controllerpublic class StaticResourceController { @RequestMapping("/static/**") public void getHtml(HttpServletRequest request, HttpServletResponse response) { String uri = request.getRequestURI(); String[] arr = uri.split("static/"); String resourceName = "index.html"; if (arr.length > 1) { resourceName = arr[1]; } String url = StaticResourceController.class.getResource("/").getPath() + "html/" + resourceName; try { FileReader reader = new FileReader(new File(url)); BufferedReader br = new BufferedReader(reader); StringBuilder sb = new StringBuilder(); String line = br.readLine(); while (line != null) { sb.append(line); line = br.readLine(); } response.getOutputStream().write(sb.toString().getBytes()); response.flushBuffer(); } catch (IOException e) { e.printStackTrace(); } }}The implementation process is very simple, which is to first separate the resource uri from the path, then read the file from the static directory, and output it to the front end. Because it is only a simple demonstration, only text-type files are processed here, and image files can be processed similarly. Of course, we will definitely not do this in reality, and Spring boot will definitely have a better solution. However, although this method is a bit stupid, it is indeed the most essential thing. No matter how convenient the framework helps us deal with this kind of problem, but aside from the framework, we still need to be able to write a web project proficiently. Only by knowing the implementation principle can you be able to be able to handle problems when you encounter problems. Now let’s take a look at Spring boot’s support for static resources.
2. Spring boot default static resource access method
Spring boot can directly access files in four directories by default:
classpath:/public/
classpath:/resources/
classpath:/static/
classpath:/META-INFO/resouces/
We now create the following four directories in the resource file resources directory:
Note that the resource folder resources under the blue bar is different from the folder classpath:/resources under the classpath. The resources under the blue bar represent that the files in the directory are resource files. When packaging, all the files in the directory will be packaged. This name can be changed. You can specify the resource directory in pom.xml:
<resources> <resource> <directory>src/main/resources</directory> </resource></resources>
The resources under the classpath are one of the default static resource folders of spring boot, and the functions are the same as public, static and MEAT-INFO/resources. Now we can restart Spring boot and we can pass
http://localhost:8080/1.html
http://localhost:8080/2.html
http://localhost:8080/3.html
http://localhost:8080/4.html
Four URLs access static resources under four directories.
3. Customize the static resource directory
Through the second section, we already know the directory of static resources that Spring boot can access by default, but everyone will definitely think, is this directory fixed? Can we define static resource directories ourselves? The answer is yes. We now customize a static resource directory. We define an images directory to store images. All /image/** paths will access resources in the images directory:
@Configurationpublic class ImageMvcConfig extends WebMvcConfigurerAdapter { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/image/**") .addResourceLocations("classpath:/images/"); }}This code should be relatively simple. @Configuration identifies a configuration class, which has been mentioned many times in the previous article. WebMvcConfigurerAdapter is an adapter for configuring mvc provided by Spring. It has many configuration methods. addResourceHandlers is a method that specializes in handling static resources. We will talk about other methods later. Now we are verifying whether the above configuration is valid. I put a spring.jpg image under the images directory. Now we access the image through http://localhost:8080/image/spring.jpg:
In fact, in addition to the above method, there is another simpler method, which is to configure it directly in application.yml:
spring: mvc: static-path-pattern: /image/** resources: static-locations: classpath:/images/
static-path-pattern: Access mode, default is /**, multiple can be separated by comma
static-locations: resource directory, comma-separated by multiple directories, the default resource directory is classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/
Note that this configuration will overwrite the default static resource directory of Spring boot. For example, if configured in the example, you can no longer access resources in static, public, resources, etc. directories.
4. Summary
This article mainly shares with you how Spring boot handles static resources. Spring boot can access static resources under the four directories: classpath:/META-INF/resources/, classpath:/resources/, classpath:/static/, classpath:/public/ by default. We can also personalize the configuration according to our needs. Finally, it should be noted that if there are resources with the same name in these four directories, which directory will the resources under which directory will be returned first? You should be able to guess through the default order of static-locations. By default, Spring boot will return resources under /META-INF/resources first. Of course, because we can customize the value of static-locations, this priority can also be adjusted.
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.