expand

Click to jump oh ~ : SpringBoot series learning summary and extension


@[toc]

preface

  • In fact, SpringBoot things are very simple to use, because the biggest feature of SpringBoot is automatic assembly.
  • But by rote memorization is certainly not good, after all, there are too many things, time-consuming and thankless things. The following will be about SpringBoot automatic assembly source code explanation, nothing when have a look, learning ideas and ideas inside our growth is certainly very good!

1. Static resources

1.1 Static resource mapping rules

  • (1) find WebMvcAutoConfiguration. Class files

  • ② Find the addResourceHandlers method

  • ③ Source code exploration
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
			super.addResourceHandlers(registry);
			// If the resource does not exist, that is false, the log will be printed (resource processing is disabled by default)
			if (!this.resourceProperties.isAddMappings()) {
				logger.debug("Default resource handling disabled");
				return;
			}
			ServletContext servletContext = getServletContext();
			// Add static resources
			// All those /webjars/** need to go to classpath:/ meta-INF /resources/webjars/.
			addResourceHandler(registry, "/webjars/**"."classpath:/META-INF/resources/webjars/");
			addResourceHandler(registry, this.mvcProperties.getStaticPathPattern(), (registration) -> {
				registration.addResourceLocations(this.resourceProperties.getStaticLocations());
				if(servletContext ! =null) {
					registration.addResourceLocations(newServletContextResource(servletContext, SERVLET_LOCATION)); }}); }private void addResourceHandler(ResourceHandlerRegistry registry, String pattern, String... locations) {
			addResourceHandler(registry, pattern, (registration) -> registration.addResourceLocations(locations));
		}

		private void addResourceHandler(ResourceHandlerRegistry registry, String pattern, Consumer
       
         customizer)
        {
			if (registry.hasMappingForPattern(pattern)) {
				return;
			}
			ResourceHandlerRegistration registration = registry.addResourceHandler(pattern);
			customizer.accept(registration);
			registration.setCachePeriod(getSeconds(this.resourceProperties.getCache().getPeriod()));
			registration.setCacheControl(this.resourceProperties.getCache().getCachecontrol().toHttpCacheControl());
			customizeResourceHandlerRegistration(registration);
		}
Copy the code

1.2. How do I use WebJars to access static resources

  • ① Project Reference Webjars:
    • Official website: WebJars official website
    • Let’s take jquery as an example

  • Add the dependent
<dependency>
    <groupId>org.webjars</groupId>
    <artifactId>jquery</artifactId>
    <version>3.6.0</version>
</dependency>
Copy the code
  • ② Locate the JAR package

  • ③ Start the project visit and try it

  • (4) access address: http://127.0.0.1:7777/webjars/jquery/3.6.0/jquery.js

  • 5. Ok! Access successful! And you’re done!

1.3. Customize static resource paths

  • ① After introducing Webjars, you can create the following three folders in the Resources folder:

  • Add a test HTML file to public
<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>dadadingdada</h1>
</body>
</html>
Copy the code
  • Visit the following try: work done!

1.4. Sequence of static resource paths

  • Create four HTML files with the same name in different places, but with different contents, as follows:

  • (2) If all four files exist: The files in the static directory have the highest priority

  • Select * from static directory;Priority: the second highest in the public directory
    • Keep your browser cache in mind, otherwise you might see the same page

  • ④ Delete files in the public directory. Priority :404

  • (5) {static takes precedence over public; template must be redirected by controller; resources cannot be accessed from the root directory unless specified.

1.5. Specify an access path

  • 1.Once you define the path of the static folder, the original automatic configuration will be invalid!
    • Added the following information to the YML configuration file:
    • Format: static-locations: file: + Path of the static resource
spring: resources: static-locations: File :C:\Users\ DDD \Downloads\ Personal test file \dyjProject\ SRC \main\ Java \com\dyjTest\dyjProject\dyjCopy the code
  • ② Access test:

Second, the home page and icon customization

2.1 the home page

  • (1) home page source: WelcomePageHandlerMapping method
@Bean
		public WelcomePageHandlerMapping welcomePageHandlerMapping(ApplicationContext applicationContext, FormattingConversionService mvcConversionService, ResourceUrlProvider mvcResourceUrlProvider) {
			WelcomePageHandlerMapping welcomePageHandlerMapping = new WelcomePageHandlerMapping(
					new TemplateAvailabilityProviders(applicationContext), applicationContext, getWelcomePage(),// Get the home page, the welcome page
					this.mvcProperties.getStaticPathPattern());
			welcomePageHandlerMapping.setInterceptors(getInterceptors(mvcConversionService, mvcResourceUrlProvider));
			welcomePageHandlerMapping.setCorsConfigurations(getCorsConfigurations());
			return welcomePageHandlerMapping;
		}
Copy the code
  • (2) getWelcomePage ()
public FlashMapManager flashMapManager(a) {
			return super.flashMapManager();
		}

		private Resource getWelcomePage(a) {
			for (String location : this.resourceProperties.getStaticLocations()) {
				Resource indexHtml = getIndexHtml(location);
				if(indexHtml ! =null) {
					return indexHtml;
				}
			}
			ServletContext servletContext = getServletContext();
			if(servletContext ! =null) {
				return getIndexHtml(new ServletContextResource(servletContext, SERVLET_LOCATION));
			}
			return null;
		}
		// The welcome page is just the index.html of a location
		private Resource getIndexHtml(Resource location) {
			try {
				Resource resource = location.createRelative("index.html");
				if(resource.exists() && (resource.getURL() ! =null)) {
					returnresource; }}catch (Exception ex) {
			}
			return null;
		}
Copy the code
  • ③ Welcome page, static resources folder under all index.html pages; Mapped by /**.

    • For example, if I visit http://localhost:7777/, I look for index.html in the static resources folder
    • Create a new index.html file in one of the three directories above us; Then visit the test http://localhost:7777/ to see the results!

2.2 the icon

  • ① Turn off the default icon first: It is recommended that the SpringBoot version be reduced to 2.1.7, because this is not available in the latest version

  • ② Add the configuration to YML
spring:
  mvc:
    favicon:
      enabled: false
Copy the code
  • Add favicon.ico to the static directory

  • ④ Clear the browser cache and visit !!!! carefully

I see a long way to go, I’ll keep searching. If you think I’m a good blogger! Writing is not easy, please like, pay attention, comment to the blogger an encouragement bar ~ reprint please indicate the source oh ~