 
      
      
    2021-3-18 前端達人
SpringBoot與Web開發(fā)(超詳細)
一、簡介
二、SpringBoot對靜態(tài)資源的映射規(guī)則
1、所有 /webjars/ ,都去 classpath:/META-INF/resources/webjars/ 找資源
2、"/" 訪問當前項目的任何資源,都去靜態(tài)資源的文件夾找映射
3、歡迎頁: 靜態(tài)資源文件夾下的所有index.html頁面,被"/"映射
三、模板引擎
1、引入Thymeleaf
2、Thymeleaf的使用
1、導入thymeleaf的名稱空間
2、使用thymeleaf語法
3、Thymeleaf的語法規(guī)則
四、SpringMVC自動配置
1、Spring MVC auto-configuration
2、擴展SpringMVC
原理
3、全面接管SpringMVC
原理
五、如何修改SpringBoot的默認配置
一、簡介
使用SpringBoot的步驟:
1、創(chuàng)建SpringBoot應用,選中我們需要的模塊。
2、SpringBoot已經(jīng)默認將這些場景配置好了,只需要在配置文件中指定少量配置就可以運行起來。
3、自己編寫業(yè)務代碼。
自動配置原理:
xxxxAutoConfiguration:幫我們給容器中自動配置組件
xxxxProperties:配置類來封裝配置文件的內(nèi)容
1
2
二、SpringBoot對靜態(tài)資源的映射規(guī)則
@ConfigurationProperties(prefix = "spring.resources", ignoreUnknownFields = false)
public class ResourceProperties implements ResourceLoaderAware {
  //可以設(shè)置和靜態(tài)資源有關(guān)的參數(shù),緩存時間等
1
2
3
WebMvcAuotConfiguration:
 @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();
          //靜態(tài)資源文件夾映射
 if (!registry.hasMappingForPattern(staticPathPattern)) {
 customizeResourceHandlerRegistration(
 registry.addResourceHandler(staticPathPattern)
 .addResourceLocations(
 this.resourceProperties.getStaticLocations())
 .setCachePeriod(cachePeriod));
 }
 }
       //配置歡迎頁映射
 @Bean
 public WelcomePageHandlerMapping welcomePageHandlerMapping(
 ResourceProperties resourceProperties) {
 return new WelcomePageHandlerMapping(resourceProperties.getWelcomePage(),
 this.mvcProperties.getStaticPathPattern());
 }
      //配置喜歡的圖標
 @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);
              //所有  /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、所有 /webjars/ ,都去 classpath:/META-INF/resources/webjars/ 找資源
webjars:以jar包的方式引入靜態(tài)資源。WebJars
訪問localhost:8080/webjars/jquery/3.3.1/jquery.js的結(jié)果:
2、"/" 訪問當前項目的任何資源,都去靜態(tài)資源的文件夾找映射
"classpath:/META-INF/resources/", 
"classpath:/resources/",
"classpath:/static/", 
"classpath:/public/" 
"/":當前項目的根路徑
例子:訪問localhost:8080/abc 就是去靜態(tài)資源文件夾里面找abc
例如我們訪問js文件夾下的Chart.min.js:
訪問結(jié)果:
3、歡迎頁: 靜態(tài)資源文件夾下的所有index.html頁面,被"/"映射
編寫index.html文件。
訪問結(jié)果:
三、模板引擎
常見的模板引擎:JSP、Velocity、Freemarker、Thymeleaf(springboot推薦,語法更簡單,功能更強大)
1、引入Thymeleaf
Thymeleaf官網(wǎng)
在pom.xml中添加以下依賴:
 <dependency>
   <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-thymeleaf</artifactId>
 </dependency>
2、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";
1
只要我們把HTML頁面放在classpath:/templates/,thymeleaf就能自動渲染。
success.html:
HelloController:
package com.keafmd.springboot.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
/
  Keafmd
 
  @ClassName: HelloController
  @Description:
  @author: 牛哄哄的柯南
  @date: 2021-03-04 19:54
 */
@Controller
public class HelloController {
    @ResponseBody
    @RequestMapping("/hello")
    public String hello(){
        return "Hello World";
    }
    @RequestMapping("/success")
    public String success() {
        return "success";
    }
}
訪問success的結(jié)果:
1、導入thymeleaf的名稱空間
<html lang="en" xmlns:th=";
1
2、使用thymeleaf語法
HelloController:
package com.keafmd.springboot.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.Map;
/*
  Keafmd
 
  @ClassName: HelloController
  @Description:
  @author: 牛哄哄的柯南
  @date: 2021-03-04 19:54
 /
@Controller
public class HelloController {
    @ResponseBody
    @RequestMapping("/hello")
    public String hello(){
        return "Hello World";
    }
    /*
      查出一些數(shù)據(jù)在頁面顯示
      @param map
      @return
     */
    @RequestMapping("/success")
    public String success(Map<String,Object> map) {
        map.put("hello","你好");
        return "success";
    }
}
success.html:
<!DOCTYPE html>
<html lang="en" xmlns:th=";
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>成功</h1>
    <!--th:text 將div里面的文本內(nèi)容設(shè)置為-->
    <div th:text="${hello}"></div>
</body>
</html>
運行結(jié)果:
3、Thymeleaf的語法規(guī)則
1、th:任意html屬性,來替換原生屬性的值
th:text — 改變當前元素里面的文本內(nèi)容
更多參考下圖:
2、表達式
Simple expressions:(表達式語法)
    Variable Expressions: ${...}:獲取變量值;OGNL;
     1)、獲取對象的屬性、調(diào)用方法
     2)、使用內(nèi)置的基本對象:
     #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)、內(nèi)置的一些工具對象:
    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: #{...}:獲取國際化內(nèi)容
    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:(數(shù)學運算)
    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: _ 
注意:內(nèi)容過多,詳細內(nèi)容參考官方文檔。
示例:↓
HelloController:
package com.keafmd.springboot.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.Arrays;
import java.util.Map;
/*
  Keafmd
 
  @ClassName: HelloController
  @Description:
  @author: 牛哄哄的柯南
  @date: 2021-03-04 19:54
 /
@Controller
public class HelloController {
    @ResponseBody
    @RequestMapping("/hello")
    public String hello(){
        return "Hello World";
    }
    /*
      查出一些數(shù)據(jù)在頁面顯示
      @param map
      @return
     */
    @RequestMapping("/success")
    public String success(Map<String,Object> map) {
        map.put("hello","你好");
        map.put("hello1","<h1>你好</h1>");
        map.put("users", Arrays.asList("柯南","小蘭","基德"));
        return "success";
    }
}
success.html:
<!DOCTYPE html>
<html lang="en" xmlns:th=";
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>成功</h1>
    <!--th:text 將div里面的文本內(nèi)容設(shè)置為-->
    <div id="div01" class="myDiv" th:id="${hello}" th:class="${hello}" th:text="${hello}">這里的內(nèi)容被覆蓋</div>
    <hr/>
    <div th:text="${hello1}"></div>
    <div th:utext="${hello1}"></div>
    <hr/>
    <!--th:each 每次遍歷都會生成當前這個標簽-->
    <h4 th:text="${user}" th:each="user:${users}"></h4>
    <hr/>
    <h4>
        <span th:each="user:${users}"> [[${user}]] </span>
    </h4>
</body>
</html>
效果:
四、SpringMVC自動配置
1、Spring MVC auto-configuration
參考官方文檔:點這里
Spring Boot 自動配置好了SpringMVC
以下是SpringBoot對SpringMVC的默認配置:(WebMvcAutoConfiguration)
Inclusion of ContentNegotiatingViewResolver and BeanNameViewResolver beans.
自動配置了ViewResolver(視圖解析器:根據(jù)方法的返回值得到視圖對象(View),視圖對象決定如何渲染(轉(zhuǎn)發(fā)?重定向?))
ContentNegotiatingViewResolver:組合所有的視圖解析器的。
如何定制:我們可以自己給容器中添加一個視圖解析器;自動的將其組合進來。
Support for serving static resources, including support for WebJars (see below).靜態(tài)資源文件夾路徑,webjars
Static index.html support. 靜態(tài)首頁訪問
Custom Favicon support (see below). favicon.ico
自動注冊了 of Converter, GenericConverter, Formatter beans.
Converter:轉(zhuǎn)換器; public String hello(User user):類型轉(zhuǎn)換使用Converter
Formatter :格式化器; 2017.12.17===Date
@Bean
@ConditionalOnProperty(prefix = "spring.mvc", name = "date-format")//在文件中配置日期格式化的規(guī)則
public Formatter<Date> dateFormatter() {
    return new DateFormatter(this.mvcProperties.getDateFormat());//日期格式化組件
}
1
2
3
4
5
自己添加的格式化器轉(zhuǎn)換器,我們只需要放在容器中即可
Support for HttpMessageConverters (see below).
HttpMessageConverter:SpringMVC用來轉(zhuǎn)換Http請求和響應的;User—Json
HttpMessageConverters 是從容器中確定;獲取所有的HttpMessageConverter
自己給容器中添加HttpMessageConverter,只需要將自己的組件注冊容器中(@Bean,@Component)
Automatic registration of MessageCodesResolver (see below):定義錯誤代碼生成規(guī)則
Automatic use of a ConfigurableWebBindingInitializer bean (see below).
我們可以配置一個ConfigurableWebBindingInitializer來替換默認的(添加到容器)
初始化WebDataBinder
請求數(shù)據(jù)=====JavaBean
1
2
org.springframework.boot.autoconfigure.web:web的所有自動場景
If you want to keep Spring Boot MVC features, and you just want to add additional MVC configuration (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.
如果你想保持Spring Boot MVC 功能,你只是想添加額外的(MVC配置)(https://docs.spring.io/spring/docs/4.3.14.RELEASE/spring-framework-reference/htmlsingle MVC)(攔截器,格式器,視圖控制器等)您可以添加自己的@ configuration類WebMvcConfigurerAdapter類型,但沒有@EnableWebMvc。如果你想提供RequestMappingHandlerMapping, RequestMappingHandlerAdapter或ExceptionHandlerExceptionResolver的自定義實例,你可以聲明一個WebMvcRegistrationsAdapter實例來提供這樣的組件。
If you want to take complete control of Spring MVC, you can add your own @Configuration annotated with @EnableWebMvc.
如果你想完全控制Spring MVC,你可以添加你自己的@Configuration注解@EnableWebMvc。
2、擴展SpringMVC
實現(xiàn)如下功能:
<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>
做法:編寫一個配置類(@Configuration),是WebMvcConfigurerAdapter類型;不能標注@EnableWebMvc
特點:既保留了所有的自動配置,也能用我們擴展的配置。
在config包下創(chuàng)建個MyMvcConfig。
代碼實現(xiàn):
package com.keafmd.springboot.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/*
  Keafmd
 
  @ClassName: MyMvcConfig
  @Description:
  @author: 牛哄哄的柯南
  @date: 2021-03-17 20:26
 /
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        //瀏覽器發(fā)送 /keafmd 請求 來到success頁面
        registry.addViewController("/keafmd").setViewName("success");
    }
}
原理
1、WebMvcAutoConfiguration是SpringMVC的自動配置類。
2、在做其他自動配置時會導入,@Import(EnableWebMvcConfiguration.class)。
   @Configuration
public static class EnableWebMvcConfiguration extends DelegatingWebMvcConfiguration {
     private final WebMvcConfigurerComposite configurers = new WebMvcConfigurerComposite();
     //從容器中獲取所有的WebMvcConfigurer
     @Autowired(required = false)
     public void setConfigurers(List<WebMvcConfigurer> configurers) {
         if (!CollectionUtils.isEmpty(configurers)) {
             this.configurers.addWebMvcConfigurers(configurers);
            //一個參考實現(xiàn);將所有的WebMvcConfigurer相關(guān)配置都來一起調(diào)用;  
            @Override
            // public void addViewControllers(ViewControllerRegistry registry) {
             //    for (WebMvcConfigurer delegate : this.delegates) {
              //       delegate.addViewControllers(registry);
              //   }
             }
         }
}
3、容器中所有的WebMvcConfigurer都會一起起作用。
4、我們的配置類也會被調(diào)用。
效果:SpringMVC的自動配置和我們的擴展配置都會起作用。
3、全面接管SpringMVC
SpringBoot對SpringMVC的自動配置不需要了,所有都是我們自己配置,所有的SpringMVC的自動配置都失效了。
做法:我們需要在配置類中添加@EnableWebMvc即可。
@EnableWebMvc
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        //瀏覽器發(fā)送 /keafmd 請求 來到success頁面
        registry.addViewController("/keafmd").setViewName("success");
    }
}
全面接管后,靜態(tài)資源失效。
不推薦這樣全面接管。
原理
加了@EnableWebMvc自動配置就失效了。
1、@EnableWebMvc的核心:
@Import({DelegatingWebMvcConfiguration.class})
public @interface EnableWebMvc {
2、DelegatingWebMvcConfiguration
@Configuration(
    proxyBeanMethods = false
)
public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport {
3、WebMvcAutoConfiguration
@Configuration(
    proxyBeanMethods = false
)
@ConditionalOnWebApplication(
    type = Type.SERVLET
)
@ConditionalOnClass({Servlet.class, DispatcherServlet.class, WebMvcConfigurer.class})
//容器中沒有這個組件的時候,這個自動配置類才生效
@ConditionalOnMissingBean({WebMvcConfigurationSupport.class})
@AutoConfigureOrder(-2147483638)
@AutoConfigureAfter({DispatcherServletAutoConfiguration.class, TaskExecutionAutoConfiguration.class, ValidationAutoConfiguration.class})
public class WebMvcAutoConfiguration {
4、@EnableWebMvc將WebMvcConfigurationSupport組件導入進來,自動配置類失效了。
5、導入的WebMvcConfigurationSupport只是SpringMVC最基本的功能。
五、如何修改SpringBoot的默認配置
1、SpringBoot在自動配置很多組件的時候,先看容器中有沒有用戶自己配置的(@Bean、@Component)如果有就用用戶配置的,如果沒有,才自動配置;如果有些組件可以有多個(ViewResolver)將用戶配置的和自己默認的組合起來。
2、在SpringBoot中會有非常多的xxxConfigurer幫助我們進行擴展配置。
3、在SpringBoot中會有很多的xxxCustomizer幫助我們進行定制配置。
以上就是SpringBoot與Web開發(fā)(超詳細)篇一的全部內(nèi)容。
————————————————
版權(quán)聲明:本文為CSDN博主「牛哄哄的柯南」的原創(chuàng)文章,遵循CC 4.0 BY-SA版權(quán)協(xié)議,轉(zhuǎn)載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/weixin_43883917/article/details/114375472
    
藍藍設(shè)計( www.bjlzjm.com.cn )是一家專注而深入的界面設(shè)計公司,為期望卓越的國內(nèi)外企業(yè)提供卓越的UI界面設(shè)計、BS界面設(shè)計 、 cs界面設(shè)計 、 ipad界面設(shè)計 、 包裝設(shè)計 、 圖標定制 、 用戶體驗 、交互設(shè)計、 網(wǎng)站建設(shè) 、平面設(shè)計服務
藍藍設(shè)計的小編 http://www.bjlzjm.com.cn