SpringBoot Series (4) ---- Web Development (1)

Ready to work

Next, we are going to use SpringBoot to develop a restful application. First, we use the Idea creation wizard to help us create a SpringBoot application and check the modules we need. Here we still only check a web scene, and then add what we need later.
Insert picture description here
SpringBoot has already configured these scenarios by default. You only need to specify a small amount of configuration in the configuration file to run, and you only need to pay attention to the business code.

SpringBoot's mapping configuration rules for static resources

Use webjars

  • A man named First SpringBoot of webjarsthings, all by pom.xmlstatic resources introduced in /webjars/**the next (this can be found in the auto-configuration class static resource), that is to say SpringBoot will automatically go to classpath:/META-INF/resources/webjars/find resources, webjars in a jarway to redistribute static package Resources (that is, we can all http://localhost:8080/webjars/xxaccess the corresponding static resources)
  • How to import static resources through pom.xml? We can go to the resource library of webjars to find, basically all the jars for static resources can be found here. We import the following dependencies in the project:
<!--    引入jquery-webjar    -->
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>jquery</artifactId>
            <version>3.4.1</version>
        </dependency>
  • After we introduce JQuery, under the dependency package of JQuery, you can see the content of webjars:
    Insert picture description here
  • Introduced the static resources of jQuery, let's start the project, and try to access it through the corresponding path. The path I used here is http://localhost:8080/webjars/jquery/3.4.1/jquery.jsthat when accessing, you only need to write the name of the resource under webjars.
    Insert picture description here

Use resources

  • What if we want to use our own static resources and don't want to use webjars? "/**"To access any resource of the current project, go to the (static resource folder) to find the mapping, that is to say, we http://localhost:8080/xxx.jsfind xxx in the static resource folder, if we don’t configure it, we will go to the following folders by default Find in
    • “classpath:/META‐INF/resources/”,
    • “classpath:/resources/”,
    • “classpath:/static/”,
    • “classpath:/public/”
    • "/": The root path of the current project

That is, through “/**”the static resources that are accessed, SpringBoot will go to the above to find resources, which are the default static resource folders of SpringBoot

  • Create two folders public and resources to store static resources to demonstrate it again.
    Insert picture description here
  • Just place Chart.min.js in one of the three folders, and then http://localhost:8080/Chart.min.jsyou can access it through
    Insert picture description here
    Insert picture description here

Configure welcome page mapping

  • Welcome page; all index.htmlpages under the static resource folder ; are "/**"mapped;
  • That is to say, we directly access the http://localhost:8080/static resource folder directly index.html, which is equivalent to our previous SpringMVC index.jsp. You can create index.htmlit under one of the three static resource folders and then run it directly. It is not a demonstration here.
  • All the same /favicon.icodefaults are found under static resources. Of course, if we don't want to use SpringBoot's default static resource folder, we can also define the mapping of static resources in the configuration file , as follows
spring.web.resources.static-locations=classpath:/cz/,classpath:/hello/

spring.web.resources.static-locations is equivalent to an array. When there are multiple folders, just use commas to separate them.
If you define the static resource mapping yourself, the default folders will not take effect, which is equivalent to the original access methods will not take effect.

Template engine

JSP, Velocity, Freemarker, Thymeleaf, etc., the essential idea of ​​the template engine is the same, but the syntax is not very consistent. For example, take freemarker as an example, as shown in the figure below.
Insert picture description here

  • Thymeleaf recommended by SpringBoot does not use JSP, because Thymeleaf has simpler syntax and more powerful functions. How to import it depends on the following:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
  • What is introduced here is the default Thymeleafdependency version of SpringBoot . If we want to switch the version, how to switch is as follows, plus the corresponding version number.
<properties>
<thymeleaf.version></thymeleaf.version>
<thymeleaf-layout-dialect.version></thymeleaf-layout-dialect.version>
</properties>

Use Thymeleaf syntax

  • Before using the Thymeleafgrammar, let’s experiment. We just need to put the HTML page in the templates directory and it Thymeleafwill be rendered automatically.
  • writeHellocintroller
@Controller
public class HelloController {
    
    
    //查出数据在页面显示
    @RequestMapping("/success")
    public String success(Map<String, Object> map) {
    
    
        map.put("success", "你好");
        return "success";
    }
}
  • In templateswriting successful pagessuccess.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>成功</h1>
    <!--th:text 将div里面的文本内容设置为 -->
    <div th:text="${success}"></div>
</body>
</html>

xmlns:th="http://www.thymeleaf.org"The introduced name space, so that when we write code, idea will have a prompt

  • After writing, we start the project, we localhost:8080/successvisit the success.htmlpage by visiting, and the result after visiting is as follows
    Insert picture description here

Grammar rules

For the specific use of Thymeleaf grammar, you can check the official documentation of Thymeleaf . I will only talk about the commonly used ones.

  • th:text; Change the text content in the current element;
    - th: any html attribute; to replace the value of the original attribute

Insert picture description here

  • expression
Simple expressions:(表达式语法)
    Variable Expressions: ${...}:获取变量值;OGNL;
    		1)、获取对象的属性、调用方法
    		2)、使用内置的基本对象:
    			#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)、内置的一些工具对象:
#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>
    
    Message Expressions: #{...}:获取国际化内容
    Link URL Expressions: @{...}:定义URL;
    		@{/order/process(execId=${execId},execType='FAST')}
    Fragment Expressions: ~{...}:片段引用表达式
    		<div th:insert="~{commons :: main}">...</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:(文本操作)
    String concatenation: +
    Literal substitutions: |The name is ${name}|
Arithmetic operations:(数学运算)
    Binary operators: + , - , * , / , %
    Minus sign (unary operator): -
Boolean operations:(布尔运算)
    Binary operators: and , or
    Boolean negation (unary operator): ! , not
Comparisons and equality:(比较运算)
    Comparators: > , < , >= , <= ( gt , lt , ge , le )
    Equality operators: == , != ( eq , ne )
Conditional operators:条件运算(三元运算符)
    If-then: (if) ? (then)
    If-then-else: (if) ? (then) : (else)
    Default: (value) ?: (defaultvalue)
Special tokens:
    No-Operation: _ 

SpringMVC automatic configuration

  • SpringBoot integrates SpringMVC, so the basic dependencies of SpringMVC operation are automatically configured in it. Then SpringBoot introduces those dependencies of SpringMVC? Here I will give a general introduction. Spring Boot provides automatic configuration for Spring MVC, which can work perfectly with most applications. You can go to the official document to view

The following is the default configuration of SpringBoot to SpringMVC: ( WebMvcAutoConfiguration)

  • Inclusion of ContentNegotiatingViewResolver and BeanNameViewResolver beans.

    • ViewResolver is automatically configured (view resolver: get the view object (View) according to the return value of the method, and the view object decides how to render (forward, redirect))
    • ContentNegotiatingViewResolver: Combine all view resolvers;
    • How to customize: we can add a view resolver to the container ourselves; automatically combine it;
  • Support for serving static resources, including support for WebJars (see below). Static resource folder path, webjars

  • Static index.htmlsupport. Static homepage access

  • Custom Favicon support (see below). favicon.ico

  • Automatically registered Converter, GenericConverter, Formatterof beans.

    • Converter: converter; public String hello(User user): use Converter for type conversion
    • FormatterFormatter; 2021.01.01==Date;
      ​ The formatter converter added by ourselves, we only need to put it in the container
		@Bean
		@ConditionalOnProperty(prefix = "spring.mvc", name = "date-format")//在文件中配置日期格式化的规则
		public Formatter<Date> dateFormatter() {
    
    
			return new DateFormatter(this.mvcProperties.getDateFormat());//日期格式化组件
		}
  • Support for HttpMessageConverters (see below).

    • HttpMessageConverter: SpringMVC is used to convert Http requests and responses; User-Json;

    • HttpMessageConverters Is determined from the container; get all HttpMessageConverter;

      Add to the container yourself HttpMessageConverter, just register your own components in the container ( @Bean,@Component)

  • Automatic registration of MessageCodesResolver(see below). Define error code generation rules

  • Automatic use of a ConfigurableWebBindingInitializer bean (see below).

    We can configure one ConfigurableWebBindingInitializerto replace the default; (add to the container)

Initialize WebDataBinder;
request data =====JavaBean;

org.springframework.boot.autoconfigure.web: all automatic scenes of the web;

If you want to keep Spring Boot MVC features, and you just want to add additional MVCconfiguration (interceptors, formatters, view controllers etc.) you can add your own @Configuration class of type WebMvcConfigurerAdapter, but without @EnableWebMvc. If you wish to provide custom instances of RequestMappingHandlerMapping, RequestMappingHandlerAdapter or ExceptionHandlerExceptionResolver you can declare a WebMvcRegistrationsAdapter instance providing such components.


If you want to take complete control of Spring MVC, you can add your own @Configuration annotated with @EnableWebMvc.

Extend SpringMVC

  • Write a springmvc configuration file:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <mvc:view-controller path="/hello" view-name="success"></mvc:view-controller>
    <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/hello"/>
            <bean></bean>
        </mvc:interceptor>
    </mvc:interceptors>
</beans>
  • Create a MyMvcConfigclass under the config package to implement the WebMvcConfigurerinterface, and you can expand the SpringMVC-related configuration in SpringBoot. WebMvcConfigurerIt can be used to extend the functions of SpringMVC, and what methods need to be implemented in it. For example, we can extend the view converter as follows
@Configuration
public class MyMvcConfig implements WebMvcConfigurer{
    
    

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
    
    
        // super.addViewControllers(registry);
        //浏览器发送 /cz 请求来到 success
        registry.addViewController("/cz").setViewName("success");
    }
}

Visiting localhost:8080/cz will jump to the success page, which not only retains the original configuration, but also can use our own way to expand the configuration

  • principle:

    • WebMvcAutoConfigurationIt is the automatic configuration class of SpringMVC
    • Will be imported when doing other automatic configuration@Import(**EnableWebMvcConfiguration**.class)
    • Everything in the container WebMvcConfigurerwill work together;
    • Our configuration class will also be called;
  • Effect : Both the automatic configuration of SpringMVC and our extended configuration will work;

If we add @EnableWebMvcannotations to the configuration class , what does it mean, that is to say, we will take over the configuration of SpringMVC in SpringBoot. All the default configurations of SpringMVC in SpringBoot will be invalid, and we need to configure ourselves, such as the above. Default webjarsaccess to static resources, etc., will fail

@EnableWebMvc
@Configuration
public class MyMvcConfig implements WebMvcConfigurer{
    
    
//....
}

Why does the @EnableWebMvcautomatic configuration fail; let’s analyze it:

  • @EnableWebMvcCore
@Import(DelegatingWebMvcConfiguration.class)
public @interface EnableWebMvc {
    
    
  • Click into the DelegatingWebMvcConfigurationcategory to view
@Configuration
public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport {
    
    
  • Then look at the automatic configuration class of SpringMVC.
@Configuration
@ConditionalOnWebApplication
@ConditionalOnClass({
    
     Servlet.class, DispatcherServlet.class,
		WebMvcConfigurerAdapter.class })
//容器中没有这个组件的时候,这个自动配置类才生效
@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE + 10)
@AutoConfigureAfter({
    
     DispatcherServletAutoConfiguration.class,
		ValidationAutoConfiguration.class })
public class WebMvcAutoConfiguration {
    
    
  • We can find that @EnableWebMvcthe WebMvcConfigurationSupportcomponents are imported in
  • WebMvcConfigurationSupportOnly the most basic functions of SpringMVC are imported ;

How to modify the default configuration of SpringBoot

  • When SpringBoot automatically configures many components, first look at whether there is any user-configured in the container ( @Bean、@Component) If there is, use the user-configured, if not, then automatically configure; if some components can have multiple (ViewResolver)user-configured and self-configured Combination of
  • There will be a lot of xxxConfigurerhelp in SpringBoot to help us expand the configuration
  • There will be a lot of xxxCustomizerhelp in SpringBoot for custom configuration

Guess you like

Origin blog.csdn.net/weixin_43844418/article/details/114019081