springboot的web開發(fā)

Ⅰ所踊、簡介

如何使用SpringBoot;
1)概荷、創(chuàng)建SpringBoot應用,選中我們需要的模塊碌燕;
2)误证、SpringBoot已經(jīng)默認將這些場景配置好了,只需要在配置文件中指定少量配置就可以運行起來
3)修壕、自己編寫業(yè)務代碼愈捅;
自動配置原理?
每當我們在創(chuàng)建項目中新增了一個模塊場景時慈鸠,我們都要考慮這個場景SpringBoot幫我們配置了什么蓝谨?我們能不能修改?我們能修改哪些配置青团?我們能不能擴展譬巫?

怎么看spring幫我們配置了什么
項目的External Libraries中有一個自動配置包,這個包下有很多的自動配置模塊:

image.png

每個模塊中會有對應的自動配置類:

xxxxAutoConfiguration:幫我們給容器中自動配置組件督笆;
xxxxProperties:配置類來封裝配置文件的內(nèi)容芦昔;

我們需要參考這個配置類,就能知道springboot幫我們自動配置了什么

Ⅱ娃肿、springboot對靜態(tài)資源的映射

springboot中org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration
類定義了一些靜態(tài)資源的默認配置咕缎,類的部分代碼如下:

@ConfigurationProperties(prefix = "spring.resources", ignoreUnknownFields = false)
public class ResourceProperties implements ResourceLoaderAware {
  //可以設置和靜態(tài)資源有關的參數(shù),緩存時間等
    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)資源晒杈;參考:http://www.webjars.org/

<!--引入jquery-webjar-->在訪問的時候只需要寫webjars下面資源的名稱即可
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>3.3.1</version>
</dependency>

2)嫂伞、"/**" 訪問當前項目的任何資源,都去(靜態(tài)資源的文件夾)找映射

"classpath:/resources/",
"classpath:/static/",
"classpath:/public/"
"/":當前項目的根路徑

localhost:8080/abc === 去靜態(tài)資源文件夾里面找abc
3)、歡迎頁末早; 靜態(tài)資源文件夾下的所有index.html頁面烟馅;被"/**"映射;
localhost:8080/ 找index頁面
4)然磷、所有的 **/favicon.ico 都是在靜態(tài)資源文件下找;
如何更改默認的資源文件路徑:

#更改默認配置靜態(tài)文件訪問路徑,如改為:類路徑下的hello文件夾郑趁,
spring.resources.static-locations=classpath:/test/
#多個路徑,逗號分隔:
spring.resources.static-locations=classpath:/test/姿搜,classpath:/test2/寡润,

Ⅲ、模板引擎

市面上的模板引擎大概有:JSP舅柜、Velocity梭纹、Freemarker、Thymeleaf

模板引擎功能圖示

SpringBoot推薦的Thymeleaf致份;語法更簡單变抽,功能更強大;thymeleaf官網(wǎng)

1).引入thymeleaf氮块;
 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
<!--不需要手動導入绍载,創(chuàng)建項目時選擇模塊那一步可以勾選idea會自動導入-->
2).thymeleaf的使用;
/**
*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");
 //規(guī)定了要thymeleaf所在的文件路徑前綴是classpath:/templates/
    public static final String DEFAULT_PREFIX = "classpath:/templates/";
 //規(guī)定了thymeleaf所在文件的后綴名是  .html
    public static final String DEFAULT_SUFFIX = ".html";
//就是說只要我們把HTML頁面放在classpath:/templates/滔蝉,thymeleaf就能自動渲染击儡;

使用:
控制器層

package com.byls.springboot;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Map;

@Controller
public class HelloController {

    @RequestMapping(value = "succeed")
    public String helloController(Map<String, String > map){
        map.put("hello","你好");
        return "index";
    }
}

頁面

<!DOCTYPE html>
<!--導入命名空間-->
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <!--${hello}直接取值,注意要卸載標簽的屬性中-->
    <div th:text="${hello}">
    直接訪問
   </div>
</body>
</html>

值得注意的是蝠引,當通過瀏覽器的導航欄阳谍,請求地址訪問頁面時,頁面會顯示的是控制器預設的值螃概,如果將該html文件復制到桌面直接訪問矫夯,頁面的返回值則是div中的“直接訪問”

3).語法規(guī)則

官方文檔傳送門
1、th:text吊洼;改變當前元素里面的文本內(nèi)容茧痒;th:任意html屬性;來替換原生屬性的值
2.表達式:

Simple expressions:(表達式語法)
  Variable Expressions: ${...}:獲取變量值融蹂;OGNL旺订;         
  Selection Variable Expressions: *{...}:選擇表達式:和${}在功能上是一樣;     
  Message Expressions: #{...}:獲取國際化內(nèi)容
  Link URL Expressions: @{...}:定義URL超燃;           
  Fragment Expressions: ~{...}:片段引用表達式
       
Literals(字面量)
  Text operations:(文本操作) 
  Arithmetic operations:(數(shù)學運算)
  Boolean operations:(布爾運算)  
  Comparisons and equality:(比較運算)
  Conditional operators:條件運算(三元運算符)
   
Special tokens:
    No-Operation: _ 

Ⅳ区拳、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());//日期格式化組件
}

? 自己添加的格式化器轉(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共郭;
    

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.
If you want to take complete control of Spring MVC, you can add your own @Configuration annotated with @EnableWebMvc.

2).如何擴展SpringMVC

編寫一個配置類(@Configuration),是WebMvcConfigurerAdapter類型除嘹;不能標注@EnableWebMvc;既保留了所有的自動配置写半,也能用我們擴展的配置;

@Configuration
// WebMvcConfigurerAdapter過時,使用WebMvcConfigurer接口
public class MyMvcConfig implements WebMvcConfigurer {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        // 瀏覽器發(fā)送 /cuzz 請求來到 success
        registry.addViewController("/cuzz").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相關配置都來一起調(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即可;

Ⅴ股囊、如何修改spring的自動配置

模式:
? 1)袜匿、SpringBoot在自動配置很多組件的時候,先看容器中有沒有用戶自己配置的(@Bean稚疹、@Component)如果有就用用戶配置的居灯,如果沒有,才自動配置;如果有些組件可以有多個(ViewResolver)將用戶配置的和自己默認的組合起來怪嫌;
? 2)义锥、在SpringBoot中會有非常多的xxxConfigurer幫助我們進行擴展配置
? 3)、在SpringBoot中會有很多的xxxCustomizer幫助我們進行定制配置

Ⅵ岩灭、RestfulCRUD

1)拌倍、默認訪問首頁
2)、國際化
3)川背、登陸

Ⅶ贰拿、禁用緩存

最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市熄云,隨后出現(xiàn)的幾起案子膨更,更是在濱河造成了極大的恐慌,老刑警劉巖缴允,帶你破解...
    沈念sama閱讀 216,692評論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件荚守,死亡現(xiàn)場離奇詭異,居然都是意外死亡练般,警方通過查閱死者的電腦和手機矗漾,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,482評論 3 392
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來薄料,“玉大人敞贡,你說我怎么就攤上這事∩阒埃” “怎么了誊役?”我有些...
    開封第一講書人閱讀 162,995評論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長谷市。 經(jīng)常有香客問我蛔垢,道長,這世上最難降的妖魔是什么迫悠? 我笑而不...
    開封第一講書人閱讀 58,223評論 1 292
  • 正文 為了忘掉前任鹏漆,我火速辦了婚禮,結果婚禮上创泄,老公的妹妹穿的比我還像新娘艺玲。我一直安慰自己,他們只是感情好鞠抑,可當我...
    茶點故事閱讀 67,245評論 6 388
  • 文/花漫 我一把揭開白布板驳。 她就那樣靜靜地躺著,像睡著了一般碍拆。 火紅的嫁衣襯著肌膚如雪若治。 梳的紋絲不亂的頭發(fā)上慨蓝,一...
    開封第一講書人閱讀 51,208評論 1 299
  • 那天,我揣著相機與錄音端幼,去河邊找鬼礼烈。 笑死,一個胖子當著我的面吹牛婆跑,可吹牛的內(nèi)容都是我干的此熬。 我是一名探鬼主播,決...
    沈念sama閱讀 40,091評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼滑进,長吁一口氣:“原來是場噩夢啊……” “哼犀忱!你這毒婦竟也來了?” 一聲冷哼從身側響起扶关,我...
    開封第一講書人閱讀 38,929評論 0 274
  • 序言:老撾萬榮一對情侶失蹤阴汇,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后节槐,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體搀庶,經(jīng)...
    沈念sama閱讀 45,346評論 1 311
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,570評論 2 333
  • 正文 我和宋清朗相戀三年铜异,在試婚紗的時候發(fā)現(xiàn)自己被綠了哥倔。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,739評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡揍庄,死狀恐怖咆蒿,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情蚂子,我是刑警寧澤沃测,帶...
    沈念sama閱讀 35,437評論 5 344
  • 正文 年R本政府宣布,位于F島的核電站缆镣,受9級特大地震影響芽突,放射性物質(zhì)發(fā)生泄漏试浙。R本人自食惡果不足惜董瞻,卻給世界環(huán)境...
    茶點故事閱讀 41,037評論 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望田巴。 院中可真熱鬧钠糊,春花似錦、人聲如沸壹哺。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,677評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽管宵。三九已至截珍,卻和暖如春攀甚,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背岗喉。 一陣腳步聲響...
    開封第一講書人閱讀 32,833評論 1 269
  • 我被黑心中介騙來泰國打工秋度, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人钱床。 一個月前我還...
    沈念sama閱讀 47,760評論 2 369
  • 正文 我出身青樓荚斯,卻偏偏與公主長得像,于是被迫代替她去往敵國和親查牌。 傳聞我的和親對象是個殘疾皇子事期,可洞房花燭夜當晚...
    茶點故事閱讀 44,647評論 2 354

推薦閱讀更多精彩內(nèi)容