This is the 18th day of my participation in the August Challenge

A list,

Use SpringBoot;

1) Create the SpringBoot application and select the module we need;

2) SpringBoot has configured these scenarios by default and only needs to specify a few configurations in the configuration file to run

3) Write business code by myself;

Spring Boot mapping rules for static resources

WebMvcAutoConfiguration.java

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    if (!this.resourceProperties.isAddMappings()) {
        logger.debug("Default resource handling disabled");
        return;
    }
    Duration cachePeriod = this.resourceProperties.getCache().getPeriod();
    CacheControl cacheControl = this.resourceProperties.getCache().getCachecontrol().toHttpCacheControl();
    if(! registry.hasMappingForPattern("/webjars/**")) {
        customizeResourceHandlerRegistration(registry.addResourceHandler("/webjars/**")
                                             .addResourceLocations("classpath:/META-INF/resources/webjars/")
                                             .setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl));
    }
    String staticPathPattern = this.mvcProperties.getStaticPathPattern();
    if(! registry.hasMappingForPattern(staticPathPattern)) { customizeResourceHandlerRegistration(registry.addResourceHandler(staticPathPattern) .addResourceLocations(getResourceLocations(this.resourceProperties.getStaticLocations())) .setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl)); }}Copy the code

All /webjars/ is in classpath:/META /resources/webjars/

Webjars: Introduce resources as JAR packages

<! Jquery webJar -->
<dependency>
    <groupId>org.webjars</groupId>
    <artifactId>jquery</artifactId>
    <version>3.3.1</version>
</dependency>
Copy the code

Access: localhost: 8080 / webjars/jquery / 3.3.1 / jquery. Js

(2) “/**” access any resources of the current project, add a custom resource file

Obtain static resource path, trace method, get:

Put static resources in one of the following folders and the project will be accessible

"classpath:/META-INF/resources/",
"classpath:/resources/", 
"classpath:/static/", 
"classpath:/public/" 
"/": The root path of the current project

// Classpath is the resources folder that comes with the project
Copy the code

(3) Welcome page, static resources folder under all index.html pages

In one of the static resources folders above, write the index.html file. Localhost :8080 is the file that appears on the first page of the visit

// Configure the welcome page mapping
@Bean
public WelcomePageHandlerMapping welcomePageHandlerMapping(ApplicationContext applicationContext, FormattingConversionService mvcConversionService, ResourceUrlProvider mvcResourceUrlProvider) {
    WelcomePageHandlerMapping welcomePageHandlerMapping = new WelcomePageHandlerMapping(
        new TemplateAvailabilityProviders(applicationContext), applicationContext, getWelcomePage(),
        this.mvcProperties.getStaticPathPattern());
    welcomePageHandlerMapping.setInterceptors(getInterceptors(mvcConversionService, mvcResourceUrlProvider));
    welcomePageHandlerMapping.setCorsConfigurations(getCorsConfigurations());
    return welcomePageHandlerMapping;
}
Copy the code

(4) Icon file, favicon.ico file in static resources folder

Does the icon not come out when accessing? Restart the project, Clean, CTRL + F5 in the browser. A set of complete

(5) Configure the static resource folder path

spring.resources.static-locations=classpath:/hello/,classpath:/world/
Copy the code

After the configuration, the default static resource folder path does not take effect

Template engine

1. Use and grammar of Thymeleaf

@ConfigurationProperties(prefix = "spring.thymeleaf")
public class ThymeleafProperties {

	private static final Charset DEFAULT_ENCODING = StandardCharsets.UTF_8;

	public static final String DEFAULT_PREFIX = "classpath:/templates/";

	public static final String DEFAULT_SUFFIX = ".html";
Copy the code

Simply place the HTML page in classpath:/templates/ and Thymeleaf will render automatically

Import the Thymeleaf namespace:

<html lang="en" xmlns:th="http://www.thymeleaf.org">
Copy the code

Grammar:

(1) Grammar rules

(Official document usingThymeleaf, 10 Attribute Precedence)

Th :text replaces the text attribute in the current element

Th: Any HTML attribute to replace the value of the native attribute

Ex. :

    <! -- Escape special characters -->
    <div th:text="${hello}"></div>
    <! -- Do not escape special characters -->
    <div th:utext="${hello}"></div>
    <hr>
    <! -- Loop over -->
    <h4 th:text="${user}" th:each="user:${users}"></h4>
    <hr>
    <h4>
        <! -- Line of writing -->
        <span th:each="user:${users}">[[${user}]]</span>
    </h4>
Copy the code

(2) expressions

(Usingthymeleaf, 4 Standard Expression Syntax)

Simple Expressions: (Expression syntax)
    Variable Expressions: ${... } get the value of the variable
    	1) Get the property of the object and call the method
    	2) Use built-in base objects
    	#ctx : the context object.
        #vars: the context variables.
        #locale : the context locale.
        #request : (only in Web Contexts) the HttpServletRequest object.
        #response : (only in Web Contexts) the HttpServletResponse object.
        #session : (only in Web Contexts) the HttpSession object.
        #servletContext : (only in Web Contexts) the ServletContext object.
        Ex. :
        	${session.foo} // Retrieves the session atttribute 'foo'
            ${session.size()}
            ${session.isEmpty()}
            ${session.containsKey('foo')}
            .
       	3) Built-in tool objects
#execInfo : information about the template being processed.
#messages : methods for obtaining externalized messages inside variables expressions, And theywould be doing this in the same way as they were using #{... } syntax.
#uris : methods for escaping parts of URLs/URIs
#conversions : methods for executing the configured conversion service (if any).
#dates : methods for java.util.Date objects: formatting, component extraction, etc.
#calendars : analogous to #dates , but for java.util.Calendar objects.
#numbers : methods for formatting numeric objects.
#strings : methods for String objects: contains, startsWith, prepending/appending, etc.
#objects : methods for objects in general.
#bools : methods for boolean evaluation.
#arrays : methods for arrays.
#lists : methods for lists.
#sets : methods for sets.
#maps : methods for maps.
#aggregates : methods for creating aggregates on arrays or collections.
#ids : methods for dealing with id attributes that might be repeated (for example, as a result of an iteration).
		Ex. :
		${#strings.isEmpty(name)}
        ${#strings.arrayIsEmpty(nameArr)}
        ${#strings.listIsEmpty(nameList)}
        .
        
    Selection Variable Expressions: *{... } select the expression, and ${} function is the same
    	Supplement: Cooperate th:object="${session.user}"
    	<div th:object="${session.user}">
            <p>Name: <span th:text="*{firstName}">Sebastian</span>.</p>
            <p>Surname: <span th:text="*{lastName}">Pepper</span>.</p>
            <p>Nationality: <span th:text="*{nationality}">Saturn</span>.</p>
        </div>
    Message Expressions: #{... } get internationalized content
    Link URL Expressions: @{... } to define URL
    	<a href="details.html" th:href="@{/order/details(orderId=${o.id},order2=${o.name})}">view
    Fragment Expressions: ~{... } fragment document reference
    	<div th:insert="~{common :: #topbar}"></div>
    
Literals
    Text literals: 'one text' , 'Another one! ',...
    Number Literals: 0, 34, 3.0, 12.3...
    Boolean literals: true , false
    Null literal: null
    Literal Tokens: One, SomeText, Main...
Text Operations :(text operations)
    String concatenation: +
    Literal substitutions: |The name is ${name}|
Arithmetic (1) The operations of mathematics
    Binary operators: + , - , * , / , %
    Minus sign (unary operator): -
Boolean (Boolean operations)
    Binary operators: and , or
    Boolean negation (unary operator): ! , not
Comparisons Equality :(comparison)
    Comparators: > , < , >= , <= ( gt , lt , ge , le )
    Equality operators: == , ! = ( eq , ne )
Conditional Operators :(conditional operation)
    If-then: (if) ? (then)
    If-then-else: (if) ? (then) : (else)
    Default: (value) ? : (defaultvalue)
Special tokens:
	No-Operation: _
Copy the code