summary
- SpringBoot development: 1. Create a SpringBoot application and select the required scenario module. 2.SpringBoot has configured the scenario module by default. You only need to specify a small number of configurations (database address, user name, password) in the configuration file to run. 3. You only need to write business logic code.
- You need to master the principle of automatic configuration: what is the default configuration of SpringBoot in this scenario, whether it can be modified, which configuration can be modified, and whether it can be extended.
XxxAutoConfiguration:Help us automatically configure components in the container XxxProperties: The configuration class encapsulates the contents of the configuration file
Spring boot mapping rules for static location
@ConfigurationProperties( prefix = "spring.resources", ignoreUnknownFields = false )
- ResourceProperties can set resource related parameters, cache time, etc.
/* * ResourceHandlerRegistry Stores the registration of a resource handler for static resources through Spring MVC services * Allows you to set cache headers optimized for efficient loading in a Web browser * Resources can be provided in the directory of the Web application, in a location other than the classpath, etc */ public void addResourceHandlers(ResourceHandlerRegistry registry) { if (!this.resourceProperties.isAddMappings()) { logger.debug("Default resource handling disabled"); } else { Duration cachePeriod = this.resourceProperties.getCache().getPeriod(); CacheControl cacheControl = this.resourceProperties.getCache().getCachecontrol().toHttpCacheControl(); if (!registry.hasMappingForPattern("/webjars/**")) { this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{"/webjars/**"}).addResourceLocations(new String[]{"classpath:/META-INF/resources/webjars/"}).setCachePeriod(this.getSeconds(cachePeriod)).setCacheControl(cacheControl)); } String staticPathPattern = this.mvcProperties.getStaticPathPattern(); if (!registry.hasMappingForPattern(staticPathPattern)) { this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{staticPathPattern}).addResourceLocations(getResourceLocations(this.resourceProperties.getStaticLocations())).setCachePeriod(this.getSeconds(cachePeriod)).setCacheControl(cacheControl)); } } }
- All / Web The resources in jars / * * are found in classpath:/META-INF/resources/webjars /.
- web.jars: introduce static resources in the form of jar package: https://www.webjars.org/
- When accessing, you only need to write web The name of the resource under jars.
/**: access any resources in the current project (folder of static resources)
classpath:/META-INF/resources/ classpath:/resources/ classpath:/static/ classpath:/public/ / # The root path of the current project
@Bean public WelcomePageHandlerMapping welcomePageHandlerMapping(ApplicationContext applicationContext) { return new WelcomePageHandlerMapping(new TemplateAvailabilityProviders(applicationContext), applicationContext, this.getWelcomePage(), this.mvcProperties.getStaticPathPattern()); }
Configure the mapping of the welcome page:
- Welcome page: all indexes under the static resource folder XML page, mapped by / * * and.
@Configuration @ConditionalOnProperty( value = {"spring.mvc.favicon.enabled"}, matchIfMissing = true ) /* * ResourceLoaderAware Is a tag interface * Used to inject ResourceLoader through ApplicationContext context * There is a setResourceLoader() method */ public static class FaviconConfiguration implements ResourceLoaderAware { private final ResourceProperties resourceProperties; /* * ResourceLoader Used to return the Resource object and ClassLoader object * - getResource(String location)Method returns the corresponding Resource object according to the provided location parameter * - getClassLoader()Method returns the ClassLoader that loads these resources */ private ResourceLoader resourceLoader; public FaviconConfiguration(ResourceProperties resourceProperties) { this.resourceProperties = resourceProperties; } public void setResourceLoader(ResourceLoader resourceLoader) { this.resourceLoader = resourceLoader; } /* * SimpleUrlHandlerMapping It is the most adaptable Handler Mapping class in spring MVC * Allows you to explicitly specify the mapping relationship between URL schema and Handler There are two ways to declare: * - prop: * - key: URL pattern * — value: Handler ID or name of * - value: * - To the left of the equal sign is the URL pattern * - To the right of the equal sign is the HandlerID or name */ @Bean public SimpleUrlHandlerMapping faviconHandlerMapping() { SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping(); mapping.setOrder(-2147483647); mapping.setUrlMap(Collections.singletonMap("**/favicon.ico", this.faviconRequestHandler())); return mapping; }
Configure favorite icons (icon of label):
- Label Icon: all * * / favicon ICOS are under static folder resources.
template engine
- jsp,velocity,freemarker,thymeleaf
advantage | shortcoming | |
---|---|---|
jsp | 1. Powerful, can write Java code 2 Support jsp tag - jsp tag3 Support expression language - EL expression 4 Official standard, widely used and rich third-party jsp tag library 5 Good performance. jsp is compiled into class file for execution, which has good performance | 1. jsp has no obvious disadvantages 2 Because Java code can be written, it is easy to destroy MVC structure if it is not used properly |
velocity | 1. Implement strict MVC separation without writing Java code 2 Good performance, superior to jsp 3 Use expression language - EL expression | 1. Not an official standard 2 Small scope of use, less third-party label libraries 3 Support for jsp tags is not friendly enough |
freemarker | 1. Implement strict MVC separation without writing Java code 2 Very good performance 3 Good support for jsp tags 4 Built in a large number of common functions, very convenient to use 5 Macro definitions (like jsp tags) are very convenient 6 Use expression language - EL expression | 1. Not an official standard 2 The scope of use is small, and there are few third-party label libraries |
thymeleaf | 1. Static html embeds tag attributes, and the browser can directly open the template file for back-end joint debugging 2 Recommended templates for springboot framework | 1. The template must comply with the xml specification 2 Need to add js script |
- freemarker:
- Freemaker is a template engine written in Java language, which generates text based on templates for output
- Freemaker has nothing to do with the Web container, that is, when the Web runs, it does not know whether it is Servlet or HTTP
- It can not only be used as the implementation technology of the presentation layer, but also be used to generate XML,JSP, Java, etc
- At present, freemaker is mainly used for static page or page display in enterprises
- Reasons for choosing freemaker:
- Performance: in terms of performance, velocity is the best, followed by jsp, and the performance of ordinary page freemaker is the worst However, on complex pages, such as those containing a large number of judgments, date and amount formatting, freemaker performs better than jsp using tag and el
- Macro definition is more convenient than jsp tag
- Built in a large number of common functions For example, html filtering, date and amount formatting, etc. are easy to use
- Support jsp Tags
- Strict mvc separation can be realized
- Freemaker vs. velocity:
- velocity:
- velocity is superior to freemaker in that it has extensive third-party support and a large user community
- velocity has the best performance
- freemarker:
- Freemaker is simpler than velocity, because velocity must write some custom toolbox es and write some general template code over and over again
- Velocity's approach makes a lot of interaction with Java objects in velocity's template, which violates the simple principle, although the code can also be transferred to the controller for implementation
- Freemaker can do it, but velocity cannot:
- Date and number support:
- Compare and format display date or time values
- Performs operations and comparisons on any number of types, including precision types, not just integers
- internationalization:
- Format number area, a variety of built-in and custom number format modes
- Format date region and time zone, a variety of built-in and customized date format modes
- Identifiers, i.e. variable names, can contain accented letters, Arabic letters, Chinese characters, etc. like non English letters
- Cyclic processing:
- Exit loop
- Internal circulation of access control variable external circulation mechanism
- Know whether the end position of the loop has been reached
- Template level array processing:
- Use the syntax of [i] to access array elements, including raw and non raw indices
- Gets the length of the array
- Macro definition:
- Macro calls can pass parameters by location or name
- Macro parameters can be set to default values. If the parameter is not specified when calling a macro, the default value will be used instead
- Macro nesting can be supported through < @ mymacro > body < / @ mymacro >
- A macro is called directly through the "macro name" expressed in text
- Macros are allowed to be used before being defined
- Macros can define local variables
- Namespace:
- Variables that use multiple namespaces This is building a "macro library"
- Built in operation methods of string, list and Map independent of Java language
- It can prompt spelling errors and other errors in the template
- When accessing a non-existent variable, freemaker will report an error when executing the template
- Through configuration, you can specify whether freemaker will stop executing or ignore the error when such an error occurs, and freemaker will record the problem in the log
- If you enter the wrong instruction name, freemaker will throw an exception
- More advanced text output tools:
- Encapsulate template blocks in a set of tags so that HTML or XML escapes (or other transformations of freemaker expressions) can be applied to ${foo} blocks
- Freemaker has a template block converter that passes through a conversion filter at render time The built - in converter includes space compressor, HTML and XML overflow You can also implement a custom converter, that is, if you generate Java source code, you can write Java code, convert it with a pretty printer, and insert it into the template At the same time, transformations can also be nested
- Use the built-in flush directive to explicitly refresh the output writer
- Stop rendering using the built-in stop directive
- Text processing:
- Supports special character processing in Java, such as \ b, \t, \n, \f, \r, \ ", \, \, and \ xXXXX in unicode
- In addition to the usual string, number and Boolean constants, you can also customize list and map text as well as internal templates
- Advanced space deletion:
- Freemaker will remove some extra spaces, skip spaces, line breaks and other characters
- Provide instructions to remove excess spaces
- Integration with other technologies:
- Provide JSP tag library to embed freemaker template in JSP
- Use directly with Python objects
- More powerful XML conversion capabilities
- Template meta program:
- Snap to any part of the output template background variable
- Arbitrarily interpreted range variables are similar to a template definition
- Date and number support:
- velocity:
thymeleaf
Basic concepts of thymeleaf
- thymeleaf is an XML, XHTML and HTML5 template engine, which can be used for Web and non Web applications
- thymeleaf's main goal: to provide a well formed template creation method that can be correctly displayed by the browser, which can be used for static modeling
- You can use thymeleaf to create validated XML and HTML templates:
- Instead of writing logical code, developers only need to add tag attributes to the template
- These tags execute pre-defined logic on the Document Object Model DOM
- thymeleaf has good scalability:
- You can use thymeleaf to customize the template attribute collection, which is used to evaluate custom expressions and use custom logic
- In this way, thymeleaf can be used as a template engine framework
Introduce thymeleaf dependency
- Introduce thymeleaf dependency in SpringBoot:
<properties> <!-- switch thymeleaf edition --> <thymeleaf.version>3.0.2.RELEASE</thymeleaf.version> <!-- Layout function support program-thymeleaf3==layout2 thymeleaf2==layout1 --> <thymeleaf-layout-dialect.version>2.1.1</thymeleaf-layout-dialect.version> </properties> <dependency> <!-- introduce thymeleaf rely on --> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
thymeleaf usage and syntax
@ConfigurationProperties( prefix = "spring.thymeleaf" ) public class ThymeleafProperties { private static final Charset DEFAULT_ENCODING; public static final String DEFAULT_PREFIX = "classpath:/templates/"; public static final String DEFAULT_SUFFIX = ".html"; private boolean checkTemplate = true; private boolean checkTemplateLocation = true; private String prefix = "classpath:/templates/"; private String suffix = ".html"; private String mode = "HTML"; private Charset encoding;
- Put the html page in classpath:/templates / and thymeleaf will render automatically.
- Use of Thymeleaf: 1. Import the namespace of thymeleaf
<html xmlns:th="http://www.thymeleaf.org">
2. Use thymeleaf syntax:
- th:text - changes the text content in the current element
- th: any html attribute - change the value of the native attribute
thymeleaf | jsp | |
---|---|---|
Fragment contains | th:insertth:replace | include |
ergodic | th:each | c:forEach |
Conditional judgment | th:ifth:unlessth:switchth:case | c:if |
Declare variable | th:objectth:with | c:set |
Any attribute modification | Th: attrth: attrprepand (front) th:attrappend (back) | |
Modify the default value of the specified attribute | th:valueth:hrefth:src | |
Modify label body text content | th:text (escape) th: utext (no escape) | |
Declaration fragment | th:fragment | |
Remove declaration fragment | th:remove |
- expression:
Simple expressions: (Expression syntax) Variable Expressions: ${...} (Get variable value-OGNL) 1.Get the properties 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. 3.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 an expression, and ${}Generally consistent in usage) Supplement: Cooperation 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> Which is exactly equivalent to: <div> <p>Name: <span th:text="${session.user.firstName}">Sebastian</span>.</p> <p>Surname: <span th:text="${session.user.lastName}">Pepper</span>.</p> <p>Nationality: <span th:text="${session.user.nationality}">Saturn</span>.</p> </div> Message Expressions: #{...} (get international content) Link URL Expressions: @{...} (definition url) <a href="details.html" th:href="@{http://localhost:8080/gtvg/order/details(orderId=${o.id})}">view</a> <!-- Will produce '/gtvg/order/details?orderId=3' (plus rewriting) --> <a href="details.html" th:href="@{/order/details(orderId=${o.id})}">view</a> <!-- Will produce '/gtvg/order/3/details' (plus rewriting) --> <a href="details.html" th:href="@{/order/{orderId}/details(orderId=${o.id})}">view</a> Fragment Expressions: ~{...} (Fragment reference expression) 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) If-then: (if) ? (then) If-then-else: (if) ? (then) : (else) Default: (value) ?: (defaultvalue) Special tokens(Special operation) No-Operation: _
Automatic configuration of spring MVC web by SpringBoot
- SpringBoot automatically configures spring MVC by default
- Viewresolver contentnegotiatingviewresolver and beannameviewresolver are automatically configured (view resolver: get the view object according to the return value of the method, and the view object decides to forward and redirect) 1.ContentNegotiatingViewResolver: combines all view parsers 1.1: how to customize the configuration - add a customized view parser to the container, and the content negotiatingviewresolver will automatically combine the customized view parsers
- Static resource folder path and web jars
- Static homepage access
- favicon.ico
- Automatically register Converter, GenericConverter, Formatter 1.Converter: converter, used for type conversion 2.GenericConverter: a universal converter that converts between multiple source types and target types. 3.Formatter: formatter - you can customize the formatter by yourself. The converter can be configured by placing it in the container
- HttpMessageConverter: used by spring MVC to convert Http requests and responses. Determine the HttpMessageConverters value from the container. You can configure the customized HttpMessageConverter by placing it in the container.
- MessageCodeResolver: define error code generation rules
- Configurable web binding initializer: initializes the web data binder, which binds the request data ConfigurableWebBindingInitializer can be configured to add to the container to replace the default
How to modify the default configuration of SpringBoot
- When SpringBoot automatically configures many components, first check whether there are configured (@ Bean, @ Component) components in the container. If so, use the configured components. If not, it will be automatically configured; If there can be multiple components, combine the configured and default configurations.
Extended MVC (cannot label @ EnableWebMvc)
- Write a configuration class (@ Configuration) that inherits WebMvcConfigurationSupport and cannot be labeled @ EnableWebMvc. All automatic configurations are retained or extended configurations can be used. During configuration, it will be imported
@Import({WebMvcAutoConfiguration.EnableWebMvcConfiguration.class})
EnableWebMvcConfiguration:
@Configuration public static class EnableWebMvcConfiguration extends DelegatingWebMvcConfiguration {
DelegatingWebMvcConfiguration:
// @Autowired( required = false ) public void setConfigurers(List<WebMvcConfigurer> configurers) { if (!CollectionUtils.isEmpty(configurers)) { this.configurers.addWebMvcConfigurers(configurers); } }
Reference implementation:
//Call all WebMvcConfigurer related configurations public void addViewControllers(ViewControllerRegistry registry) { Iterator var2 = this.delegates.iterator(); while(var2.hasNext()) { WebMvcConfigurer delegate = (WebMvcConfigurer)var2.next(); delegate.addViewControllers(registry); } }
- All webmvcconfigurers in the container will work. The configured configuration class will also be called. In this way, Spring's automatic configuration and extended configuration will work.
Take over spring MVC (@ EnableWebMvc) - not recommended
- Disable spring boot's automatic configuration of spring MVC and fully configure spring MVC. Mark @ EnableWebMvc in the configuration class. All spring MVC default configurations are disabled.
- @EnableWebMvc:
@Import({DelegatingWebMvcConfiguration.class}) public @interface EnableWebMvc { }
DelegatingWebMvcConfiguration:
@Configuration public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport {
WebMvcAutoConfiguration:
@Configuration @ConditionalOnWebApplication( type = Type.SERVLET ) @ConditionalOnClass({Servlet.class, DispatcherServlet.class, WebMvcConfigurer.class}) @ConditionalOnMissingBean({WebMvcConfigurationSupport.class}) //This autoconfiguration class takes effect when this component is not in the container @AutoConfigureOrder(-2147483638) @AutoConfigureAfter({DispatcherServletAutoConfiguration.class, TaskExecutionAutoConfiguration.class, ValidationAutoConfiguration.class})
- @Enable webmvc imports webmvc autoconfigurationsupport, excluding the spring MVC function. Summary:
- Learn more about the XxxConfigurer in SpringBoot for extended configuration