1. 程式人生 > >spring boot 尚桂谷學習筆記04 ---Web開始

spring boot 尚桂谷學習筆記04 ---Web開始

city 2.3 Go 有用 ble 獲取 source prefix des

------web開發------

  1.創建spring boot 應用 選中我們需要的模塊

  2.spring boot 已經默認將這些場景配置好了 @EnableAutoConfiguration 註解配置

    只需要在配置文件中指定少量配置 就可以運行起來

  3.自己編寫自己的邏輯代碼

    自動配置原理

    這個springboot幫助我們配置了什麽 是否可以修改 如何修改 能不能擴展。。。。。。

    xxxAutoConfiguration :幫助我們自動配置容器組件 底層調用@EnableConfigurationProperties

      @EnableConfigurationProperties(xxxPropeties.class)

底層調用 @ConfigurationProperties

        xxxConfigurationProperties:配置類來封裝配置文件內容

  spring boot 對靜態資源的映射規則:

  spring 配置文件 :spring-boot-autoconfigure-2.0.1.RELEASE.jar!\org\springframework\boot\

  autoconfigure\web\servlet\WebMvcAutoConfiguration.class

@ConfigurationProperties(
    prefix = "spring.resources",
    ignoreUnknownFields 
= false ) public class ResourceProperties { private static final String[] CLASSPATH_RESOURCE_LOCATIONS = new String[]
    {"classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/"};

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

public void addResourceHandlers(ResourceHandlerRegistry registry) {
            
if (!this.resourceProperties.isAddMappings()) { logger.debug("Default resource handling disabled"); } else { Duration cachePeriod = this.resourceProperties.getCache().getPeriod(); CacheControl cacheControl = this.resourceProperties.getCache().getCachecontrol().toHttpCacheControl(); if (!registry.hasMappingForPattern("/webjars/**")) { this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{"/webjars/**"})
              .addResourceLocations(new String[]
                {"classpath:/META-INF/resources/webjars/"})
                  .setCachePeriod(this.getSeconds(cachePeriod)).setCacheControl(cacheControl)); } String staticPathPattern = this.mvcProperties.getStaticPathPattern(); if (!registry.hasMappingForPattern(staticPathPattern)) { this.customizeResourceHandlerRegistration(
              registry.addResourceHandler(new String[]{staticPathPattern})
                .addResourceLocations(getResourceLocations(this.resourceProperties.getStaticLocations()))
                  .setCachePeriod(this.getSeconds(cachePeriod)).setCacheControl(cacheControl)); } } }

  1). 所有的/webjars/** 都去classpath:/META-INFO/resources/webjars/ 下找資源

  Webjar : 以jar包的方式引入靜態資源 http://www.webjars.org/ 參考

技術分享圖片

  引入 jquery 331版本到pom文件中 就是引入jquery了

  技術分享圖片

  localhost:8080/webjars/abc -》 都去classpath:/META-INFO/resources/webjars/下尋找

  eg: jquery實例引入 訪問可以訪問到 jquery.js 文件

技術分享圖片

  2). /** 訪問當前項目任何資源(靜態資源的文件夾 一共四個文件夾)

  技術分享圖片

    localhost:8080/abc =====》去靜態資源中訪問 abc

  3).歡迎頁 靜態資源文件夾下的 index.html 頁面 被 /** 映射

    localhost:8080/ =====》 找index 頁面

  技術分享圖片

  4).喜歡的額圖標 /favicon.ico 都是在靜態資源文件夾下尋找

  5).自己定義靜態資源文件夾後 之前的四個靜態資源文件夾路徑就不好用了

技術分享圖片

  

------引入thymeleaf------

  springboot 嵌入式tomcat 不支持jsp 的,所以需要引用模板引擎

  模板引擎:

    jsp, Velocity, thymeleaf .....

  模板引擎作用:將數據通過表達式引入到頁面中做展示

技術分享圖片

  spring boot 推薦thymeleaf :

    語法簡單 功能強大

  引入thymeleaf 框架 pom 文件 導入jar包

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

  默認使用 thymeleaf 2.--- 版本過老 可以 手動改用 3.--版本

  https://docs.spring.io/spring-boot/docs/1.5.13.BUILD-SNAPSHOT/reference/htmlsingle/

  在pom 文件的 properties中加入如下:

<properties>
    <thymeleaf.version>3.0.2.RELEASE</thymeleaf.version>
    <thymeleaf-layout-dialect.version>2.1.1</thymeleaf-layout-dialect.version>
</properties>

  通過以下 方法修改spring boot 為我們自動配置的jar包版本依賴

技術分享圖片

  Thymeleaf 使用語法:在autoconfiguration 包中找到 thymeleaf 配置文件進行配置

技術分享圖片

技術分享圖片

  thymeleaf 語法:

  使用:https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.pdf

    1 導入thymeleaf 的名稱空間

<html lang="en" xmlns:th="http://www.thymeleaf.org">

    2 使用thymeleaf 語法

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>成功</h1>
    <!-- 將div的文本內容指定為指定的值 -->
    <div th:text="${hello}">
        這是現實的歡迎信息
    </div>

</body>
</html>

  3.語法規則:

    1). th:text; 改變當前元素文本內容

      th: 任意html 屬性;用來替換原生屬性的值

技術分享圖片

    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.
    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:objiect=${session.user} 使用 *{name} 代表 ${session.user.name}
    <div th:object=${session.user}>
      <p th:*{name}/>
    </div>
  Message Expressions: #{...}: // 獲取國際化內容   Link URL Expressions: @{...} // 定義URL
    @{/order/process(execId=${execId},execType=‘FAST’)}   Fragment Expressions: ~{...} ; // 片段引用表達式
    <div th:insert="~{common::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: _

  eg : 實例

  controller 代碼

  // 查出一些數據做展示
    @RequestMapping("/success")
    public String success(Map<String, Object> map) {
        // classpath:/templates/ 跳轉到此路徑下的success.html 頁面
        map.put("hello", "<h1>你好</h1>");
        map.put("users", Arrays.asList("張三", "李四", "王五"));
        return "success";
    }

  html 代碼:其中 [[${user}]] 為不轉義 [(${user})] 為轉義user內容

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>成功</h1>
    <!-- 將div的文本內容指定為指定的值 -->
    <div th:text="${hello}">
        這是現實的歡迎信息
    </div>

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

    <!-- th:each 每次便利都會生成當前這個標簽 3個 h4-->
    <h4 th:text="${user}" th:each="user:${users}"></h4>

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

</body>
</html>

  4.springmvc 的自動配置

  eg: WebMvcAutoConfiguration.class

技術分享圖片

技術分享圖片

技術分享圖片

  org.springframework.boot.autoconfigure.web: web 配置的所有自動場景

  擴展 springmvc 比如增加 攔截器 路徑響應等等

技術分享圖片

  編寫一個配置類完成上面代碼功能 eg :

    @Configuration 是 WebMvcConfigurerAdapter 類型,不能標註@EnableWebMvc註解

    既保留了所有的自動配置 也可以用我們擴展的配置

package com.lixuchun.springboot.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

// 使用 WebMvcConfigurerAdapter 可以擴展springmvc 功能
@Configuration
public class MyMvcConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        // super.addViewControllers(registy)
        // 瀏覽器發送 /lixuchun 請求來到 success 頁面
        registry.addViewController("/lixuchun").setViewName("success");
    }

}

  頁面發送請求到 localhost:8080/lixuchun -》跳轉到 success 頁面

  原理:

    1).WebMvcAutoConfiguretion 是 springmvc 的自動配置類

    2).在做其他配置時候 會導入;@import(EnableWebMvcConfiguration.class)

技術分享圖片

    3).容器中所有的WebMvcConfigure都會一起起作用

    4). 我們的配置類也會起作用

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

  全面接管 springmvc

    springboot springmvc所有的自動配置都不用了 所有的配置都自己進行配置;

    我們需要對自己的mvc配置文件添加 @EnableWebMvc 就可以了

    --------不推薦全面接管--------

    為什麽 加上@EnableWebMvc 就全面接管了

技術分享圖片

技術分享圖片

  5. 如何修改spring boot 的默認配置:

    有統一的模式:

      1). spring boot 在自動配置組件時候 先看容器中有沒有用戶自己配置的(@Bean @Component )

      如果有則用用戶自定義的組件 在沒有的情況下才使用系統默認註入的組件,有很多組件可以有多個

      比如 (ViewResoler) 將用戶的註解配置和默認的自動裝配的配置進行結合

      2). 在springboot 中 會有很多的 xxxConfigure 幫助我們進行擴展配置

  6.RestfulCRUD 訪問

  在 template 以及 static文件夾下加入頁面以及css js img圖片

  技術分享圖片

  修改 之前的 mvc 配置文件:webMvcConfigurerAdapter 訪問 / 和 /login.html 都跳轉到 login 頁面 (templates下)

package com.lixuchun.springboot.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

// 使用 WebMvcConfigurerAdapter 可以擴展springmvc 功能
@Configuration
public class MyMvcConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        // super.addViewControllers(registy)
        // 瀏覽器發送 /lixuchun 請求來到 success 頁面
        registry.addViewController("/lixuchun").setViewName("success");
    }

    @Bean
    public WebMvcConfigurerAdapter webMvcConfigurerAdapter() {
        WebMvcConfigurerAdapter adapter = new WebMvcConfigurerAdapter() {
            @Override
            public void addViewControllers(ViewControllerRegistry registry) {
                registry.addViewController("/").setViewName("login");
                registry.addViewController("/login.html").setViewName("login");
            }
        };
        return adapter;
    }

}

  login 頁面 :引入 thymeleaf 模板,導入webjars 包下的js 以及 css文件

<!DOCTYPE html>
<!-- saved from url=(0050)http://getbootstrap.com/docs/4.0/examples/sign-in/ -->
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="">
    <link rel="icon" href="http://getbootstrap.com/favicon.ico">

    <title>Signin Template for Bootstrap</title>

    <!-- Bootstrap core CSS -->
    <link href="asserts/css/bootstrap.min.css" th:href="@{/webjars/bootstrap/4.0.0/css/bootstrap.css}" rel="stylesheet">

    <!-- Custom styles for this template -->
    <link href="asserts/css/signin.css" th:href="@{asserts/css/signin.css}" rel="stylesheet">
  </head>

  <body class="text-center">
    <form class="form-signin">
      <img class="mb-4" src="asserts/img/bootstrap-solid.svg" th:src="@{asserts/img/bootstrap-solid.svg}" alt="" width="72" height="72">
      <h1 class="h3 mb-3 font-weight-normal">Please sign in</h1>
      <label for="inputEmail" class="sr-only">Email address</label>
      <input type="email" id="inputEmail" class="form-control" placeholder="Email address" required="" autofocus="">
      <label for="inputPassword" class="sr-only">Password</label>
      <input type="password" id="inputPassword" class="form-control" placeholder="Password" required="">
      <div class="checkbox mb-3">
        <label>
          <input type="checkbox" value="remember-me"> Remember me
        </label>
      </div>
      <button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
      <p class="mt-5 mb-3 text-muted">? 2017-2018</p>
    </form>
  

</body></html>

  最後訪問:

技術分享圖片

  

  國際化:

    springmvc實現:

      編寫國際化配置文件

      使用ResourceBundleMessageSource 管理國際化資源文件

      在頁面使用fmt:message 去除國際化內容

  

    spring boot 實現

      編寫國際化配置文件 抽取頁面需要的信息:

技術分享圖片

      spring boot 已經自動 配置好了 管理國際化的資源文件的組件的組件

@EnableConfigurationProperties
public class MessageSourceAutoConfiguration {
    @Bean
    @ConfigurationProperties(
        prefix = "spring.messages"
    )

    @Bean
    public MessageSource messageSource() {
        MessageSourceProperties properties = this.messageSourceProperties();
        ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
        if (StringUtils.hasText(properties.getBasename())) {
       // 設置國際化的資源文件的基礎名稱(login.properties) 去掉語言的國家的代碼 messageSource.setBasenames(StringUtils.commaDelimitedListToStringArray(StringUtils.trimAllWhitespace(properties.getBasename()))); }
if (properties.getEncoding() != null) { messageSource.setDefaultEncoding(properties.getEncoding().name()); } messageSource.setFallbackToSystemLocale(properties.isFallbackToSystemLocale()); Duration cacheDuration = properties.getCacheDuration(); if (cacheDuration != null) { messageSource.setCacheMillis(cacheDuration.toMillis()); } messageSource.setAlwaysUseMessageFormat(properties.isAlwaysUseMessageFormat()); messageSource.setUseCodeAsDefaultMessage(properties.isUseCodeAsDefaultMessage()); return messageSource; }

      application.properties 配置基礎名稱值

        spring.messages.basename=i18n.login

      頁面進行取值:#{...}就可以取得properties值

技術分享圖片

      修改login.html文件進行國際化取值:#{...}進行取值

         [[#{login.remember}]] checkbox 是 input 標簽 不是標準<></>結構 需要特殊取值

<!DOCTYPE html>
<!-- saved from url=(0050)http://getbootstrap.com/docs/4.0/examples/sign-in/ -->
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="">
    <link rel="icon" href="http://getbootstrap.com/favicon.ico">

    <title>Signin Template for Bootstrap</title>

    <!-- Bootstrap core CSS -->
    <link href="asserts/css/bootstrap.min.css" th:href="@{/webjars/bootstrap/4.0.0/css/bootstrap.css}" rel="stylesheet">

    <!-- Custom styles for this template -->
    <link href="asserts/css/signin.css" th:href="@{asserts/css/signin.css}" rel="stylesheet">
  </head>

  <body class="text-center">
    <form class="form-signin">
      <img class="mb-4" src="asserts/img/bootstrap-solid.svg" th:src="@{asserts/img/bootstrap-solid.svg}" alt="" width="72" height="72">
      <h1 class="h3 mb-3 font-weight-normal" th:text="#{login.tip}">Please sign in</h1>
      <label for="inputEmail" class="sr-only" th:text="#{login.username}">Email address</label>
      <input type="email" id="inputEmail" th:placeholder="#{login.username}" class="form-control" placeholder="Email address" required="" autofocus="">
      <label for="inputPassword" th:text="#{login.password}" class="sr-only">Password</label>
      <input type="password" th:placeholder="#{login.password}" id="inputPassword" class="form-control" placeholder="Password" required="">
      <div class="checkbox mb-3">
        <label>
          <input type="checkbox" value="remember-me"/> [[#{login.remember}]]
        </label>
      </div>
      <button class="btn btn-lg btn-primary btn-block" type="submit" th:text="#{login.btn}">Sign in</button>
      <p class="mt-5 mb-3 text-muted">? 2017-2018</p>
   
<a class="btn btn-sm" th:href="@{/index.html(l=‘zh_CN‘)}">中文</a>
    <a class="btn btn-sm" th:href="@{/index.html(l=‘en_US‘)}">English</a>
    </form>
  

</body></html>

    之後訪問可能出現亂碼 到setting 設置 file encoding

技術分享圖片

    再次訪問 通過改變瀏覽器語言改變頁面的語言:

技術分享圖片

技術分享圖片

    現在想實現點擊頁面 中文 : 英文進行國際化實現

      原理 :國際化Locale(區域信息對象):localResolver 獲取區域信息

      默認的是根據請求頭請求信息進行國際化設置

技術分享圖片

      自己編寫一個 LocalResolver 解析器 註入到容器中 使得系統默認的解析器失效 @ConditionalOnMissingBean

      在方法上點擊 Alt + Insert 可以添加實現接口的方法

package com.lixuchun.springboot.component;

import org.springframework.lang.Nullable;
import org.springframework.web.servlet.LocaleResolver;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;

/**
 * 可以在鏈接上攜帶區域信息
 */
public class MyLocalResolver implements LocaleResolver{
    @Override
    public Locale resolveLocale(HttpServletRequest request) {
        String l = request.getParameter("l");
        Locale locale = Locale.getDefault();
        if (!StringUtils.isEmpty(l)) {
            String[] split = l.split("_");
            // 第一個語言代碼 第二個國家代碼
            locale = new Locale(split[0], split[1]);
        }
        return locale;
    }

    @Override
    public void setLocale(HttpServletRequest httpServletRequest, @Nullable HttpServletResponse httpServletResponse, @Nullable Locale locale) {

    }
}

      註入到容器中:

package com.lixuchun.springboot.config;

import com.lixuchun.springboot.component.MyLocalResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

// 使用 WebMvcConfigurerAdapter 可以擴展springmvc 功能
@Configuration
public class MyMvcConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        // super.addViewControllers(registy)
        // 瀏覽器發送 /lixuchun 請求來到 success 頁面
        registry.addViewController("/lixuchun").setViewName("success");
    }

    @Bean
    public WebMvcConfigurerAdapter webMvcConfigurerAdapter() {
        WebMvcConfigurerAdapter adapter = new WebMvcConfigurerAdapter() {
            @Override
            public void addViewControllers(ViewControllerRegistry registry) {
                registry.addViewController("/").setViewName("login");
                registry.addViewController("/index.html").setViewName("login");
            }
        };
        return adapter;
    }

    @Bean
    public LocaleResolver localeResolver() {
        return new MyLocalResolver();
    }
}

  上一篇:http://www.cnblogs.com/lixuchun/p/8969850.html

  下一篇:todo

spring boot 尚桂谷學習筆記04 ---Web開始