<thead id="kdfuf"><font id="kdfuf"></font></thead>
<samp id="kdfuf"></samp>
    <nav id="kdfuf"><strong id="kdfuf"></strong></nav>
      中文字幕无码一区二区三区在线,久久精品人人做人人爽,国产一级内射无挡观看,十八禁在线黄色网站,日韩欧美国产另类久久久精品 ,少妇人妻偷人精品一区二区,久久午夜视频,亚洲春色AⅤ无码专区

      SpringBoot與Web開發

      2021-3-18    前端達人

      SpringBoot與Web開發(超詳細)

      一、簡介

      二、SpringBoot對靜態資源的映射規則

      1、所有 /webjars/ ,都去 classpath:/META-INF/resources/webjars/ 找資源

      2、"/
      " 訪問當前項目的任何資源,都去靜態資源的文件夾找映射

      3、歡迎頁: 靜態資源文件夾下的所有index.html頁面,被"/"映射

      三、模板引擎

      1、引入Thymeleaf

      2、Thymeleaf的使用

      1、導入thymeleaf的名稱空間

      2、使用thymeleaf語法

      3、Thymeleaf的語法規則

      四、SpringMVC自動配置

      1、Spring MVC auto-configuration

      2、擴展SpringMVC

      原理

      3、全面接管SpringMVC

      原理

      五、如何修改SpringBoot的默認配置

      一、簡介

      使用SpringBoot的步驟:



      1、創建SpringBoot應用,選中我們需要的模塊。

      2、SpringBoot已經默認將這些場景配置好了,只需要在配置文件中指定少量配置就可以運行起來。

      3、自己編寫業務代碼。



      自動配置原理:



      xxxxAutoConfiguration:幫我們給容器中自動配置組件

      xxxxProperties:配置類來封裝配置文件的內容

      1

      2

      二、SpringBoot對靜態資源的映射規則

      @ConfigurationProperties(prefix = "spring.resources", ignoreUnknownFields = false)

      public class ResourceProperties implements ResourceLoaderAware {

        //可以設置和靜態資源有關的參數,緩存時間等

      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();

                //靜態資源文件夾映射

      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包的方式引入靜態資源。WebJars



      訪問localhost:8080/webjars/jquery/3.3.1/jquery.js的結果:





      2、"/
      " 訪問當前項目的任何資源,都去靜態資源的文件夾找映射

      "classpath:/META-INF/resources/", 

      "classpath:/resources/",

      "classpath:/static/", 

      "classpath:/public/" 

      "/":當前項目的根路徑



      例子:訪問localhost:8080/abc 就是去靜態資源文件夾里面找abc



      例如我們訪問js文件夾下的Chart.min.js:



      訪問結果:





      3、歡迎頁: 靜態資源文件夾下的所有index.html頁面,被"/"映射

      編寫index.html文件。



      訪問結果:





      三、模板引擎

      常見的模板引擎:JSP、Velocity、Freemarker、Thymeleaf(springboot推薦,語法更簡單,功能更強大)





      1、引入Thymeleaf

      Thymeleaf官網



      在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的結果:





      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";

          }



          /*

           
      查出一些數據在頁面顯示

            @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里面的文本內容設置為-->

          <div th:text="${hello}"></div>

      </body>

      </html>



      運行結果:





      3、Thymeleaf的語法規則

      1、th:任意html屬性,來替換原生屬性的值



      th:text — 改變當前元素里面的文本內容

      更多參考下圖:



      2、表達式



      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: _ 



      注意:內容過多,詳細內容參考官方文檔。



      示例:↓



      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";

          }



          /*

           
      查出一些數據在頁面顯示

            @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里面的文本內容設置為-->

          <div id="div01" class="myDiv" th:id="${hello}" th:class="${hello}" th:text="${hello}">這里的內容被覆蓋</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(視圖解析器:根據方法的返回值得到視圖對象(View),視圖對象決定如何渲染(轉發?重定向?))

      ContentNegotiatingViewResolver:組合所有的視圖解析器的。

      如何定制:我們可以自己給容器中添加一個視圖解析器;自動的將其組合進來。

      Support for serving static resources, including support for WebJars (see below).靜態資源文件夾路徑,webjars



      Static index.html support. 靜態首頁訪問



      Custom Favicon support (see below). favicon.ico



      自動注冊了 of Converter, GenericConverter, Formatter beans.



      Converter:轉換器; public String hello(User user):類型轉換使用Converter

      Formatter :格式化器; 2017.12.17===Date

      @Bean

      @ConditionalOnProperty(prefix = "spring.mvc", name = "date-format")//在文件中配置日期格式化的規則

      public Formatter<Date> dateFormatter() {

          return new DateFormatter(this.mvcProperties.getDateFormat());//日期格式化組件

      }

      1

      2

      3

      4

      5

      自己添加的格式化器轉換器,我們只需要放在容器中即可



      Support for HttpMessageConverters (see below).



      HttpMessageConverter:SpringMVC用來轉換Http請求和響應的;User—Json



      HttpMessageConverters 是從容器中確定;獲取所有的HttpMessageConverter



      自己給容器中添加HttpMessageConverter,只需要將自己的組件注冊容器中(@Bean,@Component)



      Automatic registration of MessageCodesResolver (see below):定義錯誤代碼生成規則



      Automatic use of a ConfigurableWebBindingInitializer bean (see below).



      我們可以配置一個ConfigurableWebBindingInitializer來替換默認的(添加到容器)



      初始化WebDataBinder

      請求數據=====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

      實現如下功能:



      <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包下創建個MyMvcConfig。



      代碼實現:



      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) {

              //瀏覽器發送 /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);

                  //一個參考實現;將所有的WebMvcConfigurer相關配置都來一起調用;  

                  @Override

                  // public void addViewControllers(ViewControllerRegistry registry) {

                   //    for (WebMvcConfigurer delegate : this.delegates) {

                    //       delegate.addViewControllers(registry);

                    //   }

                   }

               }

      }



      3、容器中所有的WebMvcConfigurer都會一起起作用。

      4、我們的配置類也會被調用。



      效果:SpringMVC的自動配置和我們的擴展配置都會起作用。



      3、全面接管SpringMVC

      SpringBoot對SpringMVC的自動配置不需要了,所有都是我們自己配置,所有的SpringMVC的自動配置都失效了。



      做法:我們需要在配置類中添加@EnableWebMvc即可。



      @EnableWebMvc

      @Configuration

      public class MyMvcConfig implements WebMvcConfigurer {

          @Override

          public void addViewControllers(ViewControllerRegistry registry) {

              //瀏覽器發送 /keafmd 請求 來到success頁面

              registry.addViewController("/keafmd").setViewName("success");

          }

      }





      全面接管后,靜態資源失效。

      不推薦這樣全面接管。





      原理

      加了@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開發(超詳細)篇一的全部內容。

      ————————————————

      版權聲明:本文為CSDN博主「牛哄哄的柯南」的原創文章,遵循CC 4.0 BY-SA版權協議,轉載請附上原文出處鏈接及本聲明。

      原文鏈接:https://blog.csdn.net/weixin_43883917/article/details/114375472


      藍藍設計www.tuitetiyu.cn )是一家專注而深入的界面設計公司,為期望卓越的國內外企業提供卓越的UI界面設計BS界面設計 、 cs界面設計 、 ipad界面設計 、 包裝設計 、 圖標定制 、 用戶體驗 、交互設計、 網站建設 平面設計服


      日歷

      鏈接

      個人資料

      藍藍設計的小編 http://www.tuitetiyu.cn

      存檔

      主站蜘蛛池模板: 国产帅男男gay网站视频| 18禁超污无遮挡无码黄网站| 国产精品国三级国产av| 芳草地社区在线视频| 亚洲日本欧美日韩高清秒播| 乐都县| 亚洲一级无码中文字幕| 色综合久久天国| 欧美视频三区| 自拍偷在线精品自拍偷无码专区| 大地资源在线资源官网| 国产精品亚洲一区二区| 无码毛片一区二区视频| 国产成人无码A区在线观看视频| 免费三级现频在线观看免费| 97无码免费人妻超级碰碰夜夜| 台南县| 精品国产一区二区三区观看不卡| 国产精品福利在线播放| 国产精品福利自产拍在线观看| 亚洲国产日韩精品一区二区 | 字幕欧美自拍一区| 中文字幕无码不卡一区二区三区| 欧洲美女黑人粗性暴交视频| 巨爆乳寡妇中文无码| 国产v片在线播放免费观| 97超碰天天摸日日碰| 武强县| 无色码中文字幕人妻| 日韩免费大片一区不卡| 暖暖 免费 高清 日本电影| 七色影视无码激情在线| 无色码中文字幕人妻| 亚洲一区二区三区十八禁| 亚洲精品国产三级在线观看| 精品处破在线播放| 少妇激情av一区二区| 在线视频亚洲欧美| 直接看很黄的免费网站| 一区二区三区国产亚洲自拍| 污网站在线看|