SpringBoot與Web開(kāi)發(fā)

2021-3-18    前端達(dá)人

SpringBoot與Web開(kāi)發(fā)(超詳細(xì))

一、簡(jiǎn)介

二、SpringBoot對(duì)靜態(tài)資源的映射規(guī)則

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

2、"/
" 訪問(wèn)當(dāng)前項(xiàng)目的任何資源,都去靜態(tài)資源的文件夾找映射

3、歡迎頁(yè): 靜態(tài)資源文件夾下的所有index.html頁(yè)面,被"/"映射

三、模板引擎

1、引入Thymeleaf

2、Thymeleaf的使用

1、導(dǎo)入thymeleaf的名稱(chēng)空間

2、使用thymeleaf語(yǔ)法

3、Thymeleaf的語(yǔ)法規(guī)則

四、SpringMVC自動(dòng)配置

1、Spring MVC auto-configuration

2、擴(kuò)展SpringMVC

原理

3、全面接管SpringMVC

原理

五、如何修改SpringBoot的默認(rèn)配置

一、簡(jiǎn)介

使用SpringBoot的步驟:



1、創(chuàng)建SpringBoot應(yīng)用,選中我們需要的模塊。

2、SpringBoot已經(jīng)默認(rèn)將這些場(chǎng)景配置好了,只需要在配置文件中指定少量配置就可以運(yùn)行起來(lái)。

3、自己編寫(xiě)業(yè)務(wù)代碼。



自動(dòng)配置原理:



xxxxAutoConfiguration:幫我們給容器中自動(dòng)配置組件

xxxxProperties:配置類(lèi)來(lái)封裝配置文件的內(nèi)容

1

2

二、SpringBoot對(duì)靜態(tài)資源的映射規(guī)則

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

public class ResourceProperties implements ResourceLoaderAware {

  //可以設(shè)置和靜態(tài)資源有關(guān)的參數(shù),緩存時(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));

}

}



       //配置歡迎頁(yè)映射

@Bean

public WelcomePageHandlerMapping welcomePageHandlerMapping(

ResourceProperties resourceProperties) {

return new WelcomePageHandlerMapping(resourceProperties.getWelcomePage(),

this.mvcProperties.getStaticPathPattern());

}



      //配置喜歡的圖標(biāo)

@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



訪問(wèn)localhost:8080/webjars/jquery/3.3.1/jquery.js的結(jié)果:





2、"/
" 訪問(wèn)當(dāng)前項(xiàng)目的任何資源,都去靜態(tài)資源的文件夾找映射

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

"classpath:/resources/",

"classpath:/static/", 

"classpath:/public/" 

"/":當(dāng)前項(xiàng)目的根路徑



例子:訪問(wèn)localhost:8080/abc 就是去靜態(tài)資源文件夾里面找abc



例如我們?cè)L問(wèn)js文件夾下的Chart.min.js:



訪問(wèn)結(jié)果:





3、歡迎頁(yè): 靜態(tài)資源文件夾下的所有index.html頁(yè)面,被"/"映射

編寫(xiě)index.html文件。



訪問(wèn)結(jié)果:





三、模板引擎

常見(jiàn)的模板引擎:JSP、Velocity、Freemarker、Thymeleaf(springboot推薦,語(yǔ)法更簡(jiǎn)單,功能更強(qiáng)大)





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頁(yè)面放在classpath:/templates/,thymeleaf就能自動(dòng)渲染。



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

    }

}



訪問(wèn)success的結(jié)果:





1、導(dǎo)入thymeleaf的名稱(chēng)空間

<html lang="en" xmlns:th=";

1

2、使用thymeleaf語(yǔ)法

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ù)在頁(yè)面顯示

      @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>



運(yùn)行結(jié)果:





3、Thymeleaf的語(yǔ)法規(guī)則

1、th:任意html屬性,來(lái)替換原生屬性的值



th:text — 改變當(dāng)前元素里面的文本內(nèi)容

更多參考下圖:



2、表達(dá)式



Simple expressions:(表達(dá)式語(yǔ)法)

    Variable Expressions: ${...}:獲取變量值;OGNL;

    1)、獲取對(duì)象的屬性、調(diào)用方法

    2)、使用內(nèi)置的基本對(duì)象:

    #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)置的一些工具對(duì)象:

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: {...}:選擇表達(dá)式:和${}在功能上是一樣;

    補(bǔ)充:配合 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: #{...}:獲取國(guó)際化內(nèi)容

    Link URL Expressions: @{...}:定義URL;

    @{/order/process(execId=${execId},execType='FAST')}

    Fragment Expressions: ~{...}:片段引用表達(dá)式

    <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ù)學(xué)運(yùn)算)

    Binary operators: + , - , * , / , %

    Minus sign (unary operator): -

Boolean operations:(布爾運(yùn)算)

    Binary operators: and , or

    Boolean negation (unary operator): ! , not

Comparisons and equality:(比較運(yùn)算)

    Comparators: > , < , >= , <= ( gt , lt , ge , le )

    Equality operators: == , != ( eq , ne )

Conditional operators:條件運(yùn)算(三元運(yùn)算符)

    If-then: (if) ? (then)

    If-then-else: (if) ? (then) : (else)

    Default: (value) ?: (defaultvalue)

Special tokens:

    No-Operation: _ 



注意:內(nèi)容過(guò)多,詳細(xì)內(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ù)在頁(yè)面顯示

      @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 每次遍歷都會(huì)生成當(dāng)前這個(gè)標(biāo)簽-->

    <h4 th:text="${user}" th:each="user:${users}"></h4>

    <hr/>

    <h4>

        <span th:each="user:${users}"> [[${user}]] </span>

    </h4>

</body>

</html>



效果:







四、SpringMVC自動(dòng)配置

1、Spring MVC auto-configuration

參考官方文檔:點(diǎn)這里



Spring Boot 自動(dòng)配置好了SpringMVC



以下是SpringBoot對(duì)SpringMVC的默認(rèn)配置:(WebMvcAutoConfiguration)



Inclusion of ContentNegotiatingViewResolver and BeanNameViewResolver beans.



自動(dòng)配置了ViewResolver(視圖解析器:根據(jù)方法的返回值得到視圖對(duì)象(View),視圖對(duì)象決定如何渲染(轉(zhuǎn)發(fā)?重定向?))

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

如何定制:我們可以自己給容器中添加一個(gè)視圖解析器;自動(dòng)的將其組合進(jìn)來(lái)。

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



Static index.html support. 靜態(tài)首頁(yè)訪問(wèn)



Custom Favicon support (see below). favicon.ico



自動(dòng)注冊(cè)了 of Converter, GenericConverter, Formatter beans.



Converter:轉(zhuǎn)換器; public String hello(User user):類(lèi)型轉(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用來(lái)轉(zhuǎn)換Http請(qǐng)求和響應(yīng)的;User—Json



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



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



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



Automatic use of a ConfigurableWebBindingInitializer bean (see below).



我們可以配置一個(gè)ConfigurableWebBindingInitializer來(lái)替換默認(rèn)的(添加到容器)



初始化WebDataBinder

請(qǐng)求數(shù)據(jù)=====JavaBean

1

2

org.springframework.boot.autoconfigure.web:web的所有自動(dòng)場(chǎng)景



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類(lèi)WebMvcConfigurerAdapter類(lèi)型,但沒(méi)有@EnableWebMvc。如果你想提供RequestMappingHandlerMapping, RequestMappingHandlerAdapter或ExceptionHandlerExceptionResolver的自定義實(shí)例,你可以聲明一個(gè)WebMvcRegistrationsAdapter實(shí)例來(lái)提供這樣的組件。



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



如果你想完全控制Spring MVC,你可以添加你自己的@Configuration注解@EnableWebMvc。



2、擴(kuò)展SpringMVC

實(shí)現(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>



做法:編寫(xiě)一個(gè)配置類(lèi)(@Configuration),是WebMvcConfigurerAdapter類(lèi)型;不能標(biāo)注@EnableWebMvc



特點(diǎn):既保留了所有的自動(dòng)配置,也能用我們擴(kuò)展的配置。



在config包下創(chuàng)建個(gè)MyMvcConfig。



代碼實(shí)現(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 請(qǐng)求 來(lái)到success頁(yè)面

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

    }

}



原理

1、WebMvcAutoConfiguration是SpringMVC的自動(dòng)配置類(lèi)。

2、在做其他自動(dòng)配置時(shí)會(huì)導(dǎo)入,@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);

            //一個(gè)參考實(shí)現(xiàn);將所有的WebMvcConfigurer相關(guān)配置都來(lái)一起調(diào)用;  

            @Override

            // public void addViewControllers(ViewControllerRegistry registry) {

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

              //       delegate.addViewControllers(registry);

              //   }

             }

         }

}



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

4、我們的配置類(lèi)也會(huì)被調(diào)用。



效果:SpringMVC的自動(dòng)配置和我們的擴(kuò)展配置都會(huì)起作用。



3、全面接管SpringMVC

SpringBoot對(duì)SpringMVC的自動(dòng)配置不需要了,所有都是我們自己配置,所有的SpringMVC的自動(dòng)配置都失效了。



做法:我們需要在配置類(lèi)中添加@EnableWebMvc即可。



@EnableWebMvc

@Configuration

public class MyMvcConfig implements WebMvcConfigurer {

    @Override

    public void addViewControllers(ViewControllerRegistry registry) {

        //瀏覽器發(fā)送 /keafmd 請(qǐng)求 來(lái)到success頁(yè)面

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

    }

}





全面接管后,靜態(tài)資源失效。

不推薦這樣全面接管。





原理

加了@EnableWebMvc自動(dòng)配置就失效了。



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

//容器中沒(méi)有這個(gè)組件的時(shí)候,這個(gè)自動(dòng)配置類(lèi)才生效

@ConditionalOnMissingBean({WebMvcConfigurationSupport.class})

@AutoConfigureOrder(-2147483638)

@AutoConfigureAfter({DispatcherServletAutoConfiguration.class, TaskExecutionAutoConfiguration.class, ValidationAutoConfiguration.class})

public class WebMvcAutoConfiguration {



4、@EnableWebMvc將WebMvcConfigurationSupport組件導(dǎo)入進(jìn)來(lái),自動(dòng)配置類(lèi)失效了。



5、導(dǎo)入的WebMvcConfigurationSupport只是SpringMVC最基本的功能。



五、如何修改SpringBoot的默認(rèn)配置

1、SpringBoot在自動(dòng)配置很多組件的時(shí)候,先看容器中有沒(méi)有用戶自己配置的(@Bean、@Component)如果有就用用戶配置的,如果沒(méi)有,才自動(dòng)配置;如果有些組件可以有多個(gè)(ViewResolver)將用戶配置的和自己默認(rèn)的組合起來(lái)。

2、在SpringBoot中會(huì)有非常多的xxxConfigurer幫助我們進(jìn)行擴(kuò)展配置。

3、在SpringBoot中會(huì)有很多的xxxCustomizer幫助我們進(jìn)行定制配置。



以上就是SpringBoot與Web開(kāi)發(fā)(超詳細(xì))篇一的全部?jī)?nèi)容。

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

版權(quán)聲明:本文為CSDN博主「牛哄哄的柯南」的原創(chuàng)文章,遵循CC 4.0 BY-SA版權(quán)協(xié)議,轉(zhuǎn)載請(qǐng)附上原文出處鏈接及本聲明。

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


藍(lán)藍(lán)設(shè)計(jì)www.bouu.cn )是一家專(zhuān)注而深入的界面設(shè)計(jì)公司,為期望卓越的國(guó)內(nèi)外企業(yè)提供卓越的UI界面設(shè)計(jì)、BS界面設(shè)計(jì) 、 cs界面設(shè)計(jì) 、 ipad界面設(shè)計(jì) 、 包裝設(shè)計(jì) 、 圖標(biāo)定制 、 用戶體驗(yàn) 、交互設(shè)計(jì)、 網(wǎng)站建設(shè) 、平面設(shè)計(jì)服務(wù)


分享本文至:

日歷

鏈接

個(gè)人資料

存檔