Web development for SpringBoot

  • An overview of the
  • SpringBoot mapping rule for static-location
  • A template engine
    • thymeleaf
      • Basic concepts of Thymeleaf
      • Introduce the Thymeleaf dependency
    • Thymeleaf usage and syntax
  • SpringBoot is the main automatic configuration of the Web for SpringMVC
  • How do I change the default SpringBoot configuration
    • Extend MVC (cannot annotate @enableWebMVC)
    • Full takeover of SpringMVC (@enableWebMVC) – not recommended

An overview of the

  • SpringBoot development: 1. Create a SpringBoot application and select the required scenario module. 2.SpringBoot has already configured the scenario module by default. You only need to specify a few configurations (database address, user name, password) in the configuration file to run. 3. Just code the business logic.
  • You need to master the principle of automatic configuration: what SpringBoot has been configured by default in this scenario, whether it can be modified, which configuration can be modified, and whether it can be extended.
XxxAutoConfiguration: helps us to auto-configure components in the container XxxProperties: configuration class, encapsulates the contents of the configuration fileCopy the code

SpringBoot mapping rule for static-location


@ConfigurationProperties( prefix = "spring.resources", ignoreUnknownFields = false )
Copy the code
  • ResourceProperties allows you to set parameters related to the resource, cache time, and so on.

 /* * ResourceHandlerRegistry stores the registry of resource handlers used to static resources through Spring MVC services * allows caching headers optimized for efficient loading in Web browsers * can provide resources in locations other than the Web application's directory, 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)); }}}Copy the code
  • All the resources in /web.jars/** are found in classpath:/ meta-INF /resources/webjars/.
  • Web. jars: Introduce static resources as jars: www.webjars.org/
  • To access, just write the name of the resource under web.jars.
  1. /**: Access any resources of the current project (folder of static resources)
Classpath :/ meta-INF /resources/ classpath:/resources/ classpath:/static/ classpath:/public/ / # Root path of the current projectCopy the code
 @Bean
        public WelcomePageHandlerMapping welcomePageHandlerMapping(ApplicationContext applicationContext) {
            return new WelcomePageHandlerMapping(new TemplateAvailabilityProviders(applicationContext), applicationContext, this.getWelcomePage(), this.mvcProperties.getStaticPathPattern());
        }
Copy the code

Configure the welcome page mapping:

  • Welcome page: all index. XML pages in the static resources folder are mapped by /**.
        @Configuration
        @ConditionalOnProperty( value = {"spring.mvc.favicon.enabled"}, matchIfMissing = true )

		/* * ResourceLoaderAware is a tag interface * for injecting ResourceLoader through the ApplicationContext * has the setResourceLoader() method */
        public static class FaviconConfiguration implements ResourceLoaderAware {
            private final ResourceProperties resourceProperties;
            /* * ResourceLoader is used to return Resource objects and ClassLoader objects * -getResource (String location) method returns the corresponding Resource object * - based on the provided location parameter The getClassLoader() method returns the ClassLoader */ that loaded these resources
            private ResourceLoader resourceLoader;

            public FaviconConfiguration(ResourceProperties resourceProperties) {
                this.resourceProperties = resourceProperties;
            }

            public void setResourceLoader(ResourceLoader resourceLoader) {
                this.resourceLoader = resourceLoader;
            }

			/* * SimpleUrlHandlerMapping is the most adaptable HandlerMapping class in SpringMVC. There are two declarations: * -prop: * -key: URL mode * -value: specifies the ID or name of the Handler * - value: * - The URL mode * - the HandlerID or name */ is on the left of the equals sign
            @Bean
            public SimpleUrlHandlerMapping faviconHandlerMapping(a) {
                SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
                mapping.setOrder(-2147483647);
                mapping.setUrlMap(Collections.singletonMap("**/favicon.ico".this.faviconRequestHandler()));
                return mapping;
            }
Copy the code

Configure favorite ICONS (label ICONS) :

  • Label ICONS: All **/favicon.ico are under static folder resources.

A template engine

  • JSP, Velocity, Freemarker, Thymeleaf
advantages disadvantages
jsp 1. Powerful and writableJavaCode 2. SupportjspTags –jsp tag3. Support expression language –ELExpression 4. Official standard, widely used, rich third partyjspLabel library 5. Good performance,jspCompiled intoclassFile execution, with good performance 1. JSP has no obvious disadvantages 2. Since Java code can be written, improper use can easily break the MVC structure
velocity 1. Don’t writeJavaCode to implement strictMVCSeparation 2. Good performance thanjsp3. Use expression language –ELexpression 1. It is not an official standard. 2. rightjspTag support is not friendly enough
freemarker 1. Don’t writeJavaCode to implement strictMVCSeparation 2. Very good performance 3jspGood label support 4. Built-in a large number of common functions, very easy to use 5. Macro definition (similarjsp6. Use expression language –ELexpression 1. It is not an official standard. 2
thymeleaf 1. The statichtmlEmbedded tag attributes, the browser can directly open the template file, easy to back-end interconnect 2.SpringBootRecommended Framework Template 1. The template must meet the requirementsxmlSpecification 2. Need to be addedjsThe script
  • freemarker:

    • Freemarker is a template engine written in the Java language that generates text based on templates for output

    • Freemarker is independent of the Web container, that is, at Web runtime, you don’t know if it’s a Servlet or HTTP

    • Not only can it be used as a presentation layer implementation technique, but it can also be used to generate XML,JSP, or Java, etc

    • Freemarker is currently primarily used in enterprises for static pages or page presentation

    • Reasons for choosing Freemarker:

      • Performance: In terms of performance, Velocity is the best, followed by JSP, and the regular page freemarker is the worst. But on complex pages, such as pages with a lot of judgment, date-amount formatting, Freemarker performs better than JSPS using Tag and EL
      • Macro definitions are more convenient than JSP tags
      • Lots of common features are built in. Such as HTML filtering, date amount formatting and so on, easy to use
      • Support for JSP tags
      • Strict equal MVC separation can be achieved
  • Freemarker vs. Velocity:

    • velocity:

      • Velocity is superior to Freemarker in that it has extensive third-party support and a large user community
      • Velocity has the best performance
    • freemarker:

      • Freemarker is simpler than Velocity because Velocity has to write some custom Toolbox and write generic template code over and over again

      • Velocity’s approach to interacting heavily with Java objects in the Velocity template violates the principle of simplicity, although it is also possible to implement code in a controller

      • Freemarker can do what Velocity can’t:

        • Date and number support:

          • Compare and format display date or time values
          • Perform 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 regions and time zones, a variety of built-in and custom date format modes
          • Identifiers, that is, variable names can contain non-English accented letters, Arabic letters, Chinese characters, etc
        • Cycle processing:

          • Exit the loop
          • Access control variable outer loop mechanism internal loop
          • To know if the current end of the loop is reached
        • Template level array handling:

          • Use the syntax [I] to access array elements, both raw and non-raw exponents
          • Gets the length of the array
        • Macro definition:

          • Macro calls can pass arguments by location or name
          • Macro parameters can be set to default values. If this parameter is not specified when the macro is called, the default value is used instead
          • Macro nesting is supported by < @mymacro >body< / @mymacro >
          • A macro is invoked directly with a text-expressed macro name
          • Macros allow use before definition
          • Macros can define local variables
        • Namespace:

          • Variables that use multiple namespaces. This is building a macro library.
        • Built-in Java language independent string, list,Map operation methods

        • Can indicate spelling errors and other errors in templates

          • Freemarker will report an error when executing the template when accessing a variable that does not exist
          • Configuration allows you to specify whether Freemarker stops execution if such an error occurs, or ignores it, and Freemarker logs the problem
          • Enter the wrong directive name and Freemarker will throw an exception
        • More advanced text output tools:

          • Encapsulate the template block in a set of tags so that HTML or XML escapes (or other conversions of freemarker expressions) can be applied to the ${foo} block
          • Freemarker has converters for template blocks that pass through conversion filters at render time. Built-in converters include space compressors,HTML and XML overflow. Custom converters can also be implemented, that is, if Java source code is generated, you can write a Java code pretty printer transform and plug it into the template. 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 Java special character handling, such as \b, \t, \n, \f, \r, \ “, \ ‘, \, and Unicode \xXXXX
          • In addition to the usual strings, numbers, and Boolean constants, you can also customize list and map text as well as internal templates
        • Advanced space deletion:

          • Freemarker will remove extra Spaces, tabs, line feeds, etc
          • Provides instructions to remove excess whitespace
        • Integration with other technologies:

          • Provide JSP tag libraries to embed freemarker templates in JSPS
          • Use it directly with Python objects
        • More powerful XML conversion capabilities

        • Template metaprogram:

          • Capture any part of the output template background variable
          • Arbitrarily interpreted range variables, like a template definition

thymeleaf

Basic concepts of Thymeleaf

  • Thymeleaf is an XML,XHTML,HTML5 template engine for Web and non-Web applications

  • Thymeleaf’s main goal: to provide a well-formed way to create templates that can be displayed correctly by browsers and used for static modeling

  • You can use Thymeleaf to create validated XML and HTML templates:

    • Instead of writing logical code, developers simply add tag attributes to the template
    • These tags then perform predefined logic on the DOCUMENT Object Model (DOM)
  • Thymeleaf has good scalability:

    • You can use the Thymeleaf collection of custom template properties to evaluate custom expressions and use custom logic
    • Thymeleaf can then be used as a template engine framework

Introduce the Thymeleaf dependency

  • Import the Thymeleaf dependency in SpringBoot:
		<properties>	
			<! -- Change thymeleaf version -->
			<thymeleaf.version>3.0.2. RELEASE</thymeleaf.version>
			<! Thymeleaf3 ==layout2 Thymeleaf2 ==layout1 -->
			<thymeleaf-layout-dialect.version>2.1.1</thymeleaf-layout-dialect.version>	
		</properties>
		<dependency>	
			<! -- Introduce thymeleaf dependency -->
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
Copy the code

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;
Copy the code
  • Place the HTML page in classpath:/templates/ and thymeleaf will render automatically.
  • Use Thymeleaf: 1. Import the Thymeleaf namespace
<html xmlns:th="http://www.thymeleaf.org">
Copy the code

2. Use thymeleaf syntax:

  • Th :text – Changes the text content of the current element
  • Th: Any HTML attribute – changes the value of the native attribute
thymeleaf jsp
containing th:insert th:replace include
traverse th:each c:forEach
conditional th:if th:unless th:switch th:case c:if
Declare a variable th:object th:with c:set
Arbitrary property modification Th :attr th:attrprepend th: attrAppEnd
Modifies the default values of specified properties th:value th:href th:src
Modify the label body text Th :text (escaped) th:utext(escaped)
Statement fragments th:fragment
Remove the declaration fragment th:remove
  • Expressions:
Simple Expressions: (expression syntax) Variable expressions: ${... } (get variable value -ognl) 1. Get object properties, call method 2. Use the built-in base objects: # CTX: the context object. # Vars: the context variables. #locale: the context locale. (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. #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: *{... 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: #{... } Link URL Expressions: @{... } (Define 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 expressions) 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 Manipulation) String concatenation: + Literal substitutions: | | The name is ${name} Arithmetic operations (math) Binary operators: +, -, *, /, % Minus sign (unary operator) : -Boolean operators: and, or Boolean negation (unary operator):! Word order: >, <= (gt, lt, GE, le) Equality operators: ==,! = (eq, ne) Conditional operators(Conditional operators) if-then: (If)? (then) If-then-else: (if) ? (then) : (else) Default: (value) ? : (DefaultValue) Special Tokens No-operation: _Copy the code

SpringBoot is the main automatic configuration of the Web for SpringMVC

  • SpringBoot is automatically configured with SpringMVC by default
  • Automatically configuredViewResolver-ContentNegotiatingViewResolver,BeanNameViewResolver(View resolver: Based on the return value of the method to the view object, the view object decides to forward, redirect)

    1.ContentNegotiatingViewResolver:Combine all view parsers

    1.1:How to customize the configuration – add a custom view in container parser, ContentNegotiatingViewResolver will automatically custom views parser combination in
  • Static resource folder paths and web.jars
  • Static home page access
  • favicon.ico
  • Auto register Converter, GenericConverter, Formatter

    1.Converter: converter used for type conversion

    2.GenericConverter: General-purpose converter that converts between multiple source and target types.

    3.Formatter: formatter –You can customize the formatter by placing it in a container and configuring it
  • HttpMessageConverter:SpringMVC is used to transform Http requests and responses. Determine the HttpMessageConverters value from the container.You can configure your own custom configured HttpMessageConverter in a container.
  • MessageCodeResolver: Defines error code generation rules
  • ConfigurableWebBindingInitializer:Initializes the Web data binder, which binds the request data.You can replace the default configuration ConfigurableWebBindingInitializer added to the container

How do I change the default SpringBoot configuration

  • SpringBoot will automatically configure many components by checking whether there are already configured (@bean, @Component) components in the container. If there are, they will be configured. If not, they will be automatically configured. If you can have more than one component, combine the configured one with the default configured one.

Extend MVC (cannot annotate @enableWebMVC)

  • * write a Configuration class (@ Configuration), inherit WebMvcConfigurationSupport, can’t mark @ EnableWebMvc. * All automatic configurations are retained and extended configurations can be used. It is imported during configuration
@Import({WebMvcAutoConfiguration.EnableWebMvcConfiguration.class})
Copy the code

EnableWebMvcConfiguration:

 @Configuration
    public static class EnableWebMvcConfiguration extends DelegatingWebMvcConfiguration {
Copy the code

DelegatingWebMvcConfiguration:

  //
  @Autowired( required = false )
    public void setConfigurers(List<WebMvcConfigurer> configurers) {
        if(! CollectionUtils.isEmpty(configurers)) {this.configurers.addWebMvcConfigurers(configurers); }}Copy the code

Reference implementation:

 // Call all WebMvcConfigurer configurations
 public void addViewControllers(ViewControllerRegistry registry) {
        Iterator var2 = this.delegates.iterator();

        while(var2.hasNext()) { WebMvcConfigurer delegate = (WebMvcConfigurer)var2.next(); delegate.addViewControllers(registry); }}Copy the code
  • All WebMvcConfigurer in the container will work. The configured configuration class is also called. Both Spring’s autoconfiguration and extension configuration come into play.

Full takeover of SpringMVC (@enableWebMVC) – not recommended

  • Disable SpringBoot automatic configuration of SpringMVC, and configure SpringMVC comprehensively. Annotate @enableWebMVC in the configuration class. All SpringMVC defaults are disabled.
  • @ EnableWebMvc:
@Import({DelegatingWebMvcConfiguration.class})
public @interface EnableWebMvc {
}
Copy the code

DelegatingWebMvcConfiguration:

@Configuration
public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport {
Copy the code

WebMvcAutoConfiguration:

@Configuration
@ConditionalOnWebApplication( type = Type.SERVLET )
@ConditionalOnClass({Servlet.class, DispatcherServlet.class, WebMvcConfigurer.class})
@ConditionalOnMissingBean({WebMvcConfigurationSupport.class})	This autoconfiguration class takes effect only when the component does not exist in the container
@AutoConfigureOrder(-2147483638)
@AutoConfigureAfter({DispatcherServletAutoConfiguration.class, TaskExecutionAutoConfiguration.class, ValidationAutoConfiguration.class})
Copy the code
  • @ EnableWebMvc will WebMvcAutoConfigurationSupport imported, not including for SpringMVC function. Conclusion:
  • Learn more about XxxConfigurer in SpringBoot and expand the configuration