4, Web development
1, introduction
Use SpringBoot;
1) . create a spring boot application and select the modules we need;
2) Spring boot has configured these scenarios by default. You only need to specify a few configurations in the configuration file to run them
3) . write your own business code;
Principle of automatic configuration?
What does spring boot help us to configure for this scenario? Can you modify it? What configurations can be modified? Can we expand it? xxx
xxxxAutoConfiguration: help us to automatically configure components in the container; xxxxProperties: configuration class to encapsulate the content of configuration file;
2. Spring boot's mapping rules for static resources;
@ConfigurationProperties(prefix = "spring.resources", ignoreUnknownFields = false) public class ResourceProperties implements ResourceLoaderAware { //You can set parameters related to static resources, cache time, etc
WebMvcAutoConfiguration: @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { if (!this.resourceProperties.isAddMappings()) { logger.debug("Default resource handling disabled"); return; } Integer cachePeriod = this.resourceProperties.getCachePeriod(); if (!registry.hasMappingForPattern("/webjars/**")) { customizeResourceHandlerRegistration( registry.addResourceHandler("/webjars/**") .addResourceLocations( "classpath:/META-INF/resources/webjars/") .setCachePeriod(cachePeriod)); } String staticPathPattern = this.mvcProperties.getStaticPathPattern(); //Static resource folder mapping if (!registry.hasMappingForPattern(staticPathPattern)) { customizeResourceHandlerRegistration( registry.addResourceHandler(staticPathPattern) .addResourceLocations( this.resourceProperties.getStaticLocations()) .setCachePeriod(cachePeriod)); } } //Configure welcome page mapping @Bean public WelcomePageHandlerMapping welcomePageHandlerMapping( ResourceProperties resourceProperties) { return new WelcomePageHandlerMapping(resourceProperties.getWelcomePage(), this.mvcProperties.getStaticPathPattern()); } //Configure favorite icons @Configuration @ConditionalOnProperty(value = "spring.mvc.favicon.enabled", matchIfMissing = true) public static class FaviconConfiguration { private final ResourceProperties resourceProperties; public FaviconConfiguration(ResourceProperties resourceProperties) { this.resourceProperties = resourceProperties; } @Bean public SimpleUrlHandlerMapping faviconHandlerMapping() { SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping(); mapping.setOrder(Ordered.HIGHEST_PRECEDENCE + 1); //All **/favicon.ico mapping.setUrlMap(Collections.singletonMap("**/favicon.ico", faviconRequestHandler())); return mapping; } @Bean public ResourceHttpRequestHandler faviconRequestHandler() { ResourceHttpRequestHandler requestHandler = new ResourceHttpRequestHandler(); requestHandler .setLocations(this.resourceProperties.getFaviconLocations()); return requestHandler; } }
1) , all / webjars / * *, go to classpath:/META-INF/resources/webjars / to find resources;
webjars: static resources are introduced by jar package;
http://www.webjars.org/
localhost:8080/webjars/jquery/3.3.1/jquery.js
<! -- introduce jQuery webjar -- > when accessing, you only need to write the name of the resource under webjars <dependency> <groupId>org.webjars</groupId> <artifactId>jquery</artifactId> <version>3.3.1</version> </dependency>
2) "/ * *" to access any resources of the current project, go to (the folder of static resources) to find the mapping
"classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/" '/': the root path of the current project
localhost:8080/abc = = = go to the static resource folder to find abc
3) , welcome page; all index.html pages under the static resource folder; mapped by "/ * *;
localhost:8080 / find the index page
4) , all * * / favicon.ico s are found under the static resource file;
3. Template engine
JSP,Velocity,Freemarker,Thymeleaf
Thymeleaf recommended by SpringBoot;
The grammar is simpler and more powerful;
1. Introducing thymeleaf;
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> 2.1.6 </dependency> //Switch thymeleaf version <properties> <thymeleaf.version>3.0.9.RELEASE</thymeleaf.version> <!-- Support program for layout function thymeleaf3 main program layout2 Above version --> <!-- thymeleaf2 layout1--> <thymeleaf-layout-dialect.version>2.2.2</thymeleaf-layout-dialect.version> </properties>
2. Use of Thymeleaf
@ConfigurationProperties(prefix = "spring.thymeleaf") public class ThymeleafProperties { private static final Charset DEFAULT_ENCODING = Charset.forName("UTF-8"); private static final MimeType DEFAULT_CONTENT_TYPE = MimeType.valueOf("text/html"); public static final String DEFAULT_PREFIX = "classpath:/templates/"; public static final String DEFAULT_SUFFIX = ".html"; //
As long as we put the HTML page in classpath:/templates /, thmeleaf can render automatically;
Use:
1. Import namespace of thymeleaf
<html lang="en" xmlns:th="http://www.thymeleaf.org">
2. Using thmeleaf syntax;
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>Success!</h1> <!--th:text take div The text content is set as --> <div th:text="${hello}">This is a welcome message</div> </body> </html>
3. Grammatical rules
1) , th:text; change the text content in the current element;
th: any html attribute; to replace the value of the native attribute
2) , expression?
Simple expressions:(Expression syntax) Variable Expressions: ${...}: Get the variable value; OGNL; 1),Get object properties, call methods 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. ${session.foo} 3),Some built-in tool objects: #execInfo : information about the template being processed. #messages : methods for obtaining externalized messages inside variables expressions, in the same way as they would be obtained 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). Selection Variable Expressions: *{...}: Select expressions: and ${}It is the same in function; //Add: with 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 international content Link URL Expressions: @{...}: Definition URL; @{/order/process(execId=${execId},execType='FAST')} Fragment Expressions: ~{...}: Fragment reference expression <div th:insert="~{commons :: main}">...</div> Literals(Literal) 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 operation) String concatenation: + Literal substitutions: |The name is ${name}| Arithmetic operations:(Mathematical operation) Binary operators: + , - , * , / , % Minus sign (unary operator): - Boolean operations:(Boolean operation) Binary operators: and , or Boolean negation (unary operator): ! , not Comparisons and equality:(Comparison operation) Comparators: > , < , >= , <= ( gt , lt , ge , le ) Equality operators: == , != ( eq , ne ) Conditional operators:Conditional operation (ternary operator) If-then: (if) ? (then) If-then-else: (if) ? (then) : (else) Default: (value) ?: (defaultvalue) Special tokens: No-Operation: _