1. 程式人生 > 實用技巧 >四、Web開發 1

四、Web開發 1

四、Web開發

1、簡介

使用SpringBoot;

1)、建立SpringBoot應用,選中我們需要的模組;

2)、SpringBoot已經預設將這些場景配置好了,只需要在配置檔案中指定少量配置就可以執行起來

3)、自己編寫業務程式碼;

自動配置原理?

這個場景SpringBoot幫我們配置了什麼?能不能修改?能修改哪些配置?能不能擴充套件?xxx

xxxxAutoConfiguration:幫我們給容器中自動配置元件;
xxxxProperties:配置類來封裝配置檔案的內容;

2、SpringBoot對靜態資源的對映規則;

@ConfigurationProperties(prefix = "spring.resources", ignoreUnknownFields = false)
public class ResourceProperties implements ResourceLoaderAware {
  //可以設定和靜態資源有關的引數,快取時間等
	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包的方式引入靜態資源;

http://www.webjars.org/

localhost:8080/webjars/jquery/3.3.1/jquery.js

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

2)、"/**" 訪問當前專案的任何資源,都去(靜態資源的資料夾)找對映

"classpath:/META-INF/resources/", 
"classpath:/resources/",
"classpath:/static/", 
"classpath:/public/" 
"/":當前專案的根路徑

localhost:8080/abc === 去靜態資原始檔夾裡面找abc

3)、歡迎頁; 靜態資原始檔夾下的所有index.html頁面;被"/**"對映;

​ localhost:8080/ 找index頁面

4)、所有的 **/favicon.ico 都是在靜態資原始檔下找;

3、模板引擎

JSP、Velocity、Freemarker、Thymeleaf

SpringBoot推薦的Thymeleaf;

語法更簡單,功能更強大;

1、引入thymeleaf;

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
          	2.1.6
		</dependency>
切換thymeleaf版本
<properties>
		<thymeleaf.version>3.0.9.RELEASE</thymeleaf.version>
		<!-- 佈局功能的支援程式  thymeleaf3主程式  layout2以上版本 -->
		<!-- thymeleaf2   layout1-->
		<thymeleaf-layout-dialect.version>2.2.2</thymeleaf-layout-dialect.version>
  </properties>

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

只要我們把HTML頁面放在classpath:/templates/,thymeleaf就能自動渲染;

使用:

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>
    <!--th:text 將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.
                
                ${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: _ 

4、SpringMVC自動配置

https://docs.spring.io/spring-boot/docs/1.5.10.RELEASE/reference/htmlsingle/#boot-features-developing-web-applications

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());//日期格式化元件
		}

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

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

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

    <mvc:view-controller path="/hello" view-name="success"/>
    <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/hello"/>
            <bean></bean>
        </mvc:interceptor>
    </mvc:interceptors>

編寫一個配置類(@Configuration),是WebMvcConfigurerAdapter型別;不能標註@EnableWebMvc;

既保留了所有的自動配置,也能用我們擴充套件的配置;

//使用WebMvcConfigurerAdapter可以來擴充套件SpringMVC的功能
@Configuration
public class MyMvcConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
       // super.addViewControllers(registry);
        //瀏覽器傳送 /atguigu 請求來到 success
        registry.addViewController("/atguigu").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即可;

//使用WebMvcConfigurerAdapter可以來擴充套件SpringMVC的功能
@EnableWebMvc
@Configuration
public class MyMvcConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
       // super.addViewControllers(registry);
        //瀏覽器傳送 /atguigu 請求來到 success
        registry.addViewController("/atguigu").setViewName("success");
    }
}

原理:

為什麼@EnableWebMvc自動配置就失效了;

1)@EnableWebMvc的核心

@Import(DelegatingWebMvcConfiguration.class)
public @interface EnableWebMvc {

2)、

@Configuration
public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport {

3)、

@Configuration
@ConditionalOnWebApplication
@ConditionalOnClass({ Servlet.class, DispatcherServlet.class,
		WebMvcConfigurerAdapter.class })
//容器中沒有這個元件的時候,這個自動配置類才生效
@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE + 10)
@AutoConfigureAfter({ DispatcherServletAutoConfiguration.class,
		ValidationAutoConfiguration.class })
public class WebMvcAutoConfiguration {

4)、@EnableWebMvc將WebMvcConfigurationSupport元件匯入進來;

5)、匯入的WebMvcConfigurationSupport只是SpringMVC最基本的功能;

5、如何修改SpringBoot的預設配置

模式:

​ 1)、SpringBoot在自動配置很多元件的時候,先看容器中有沒有使用者自己配置的(@Bean、@Component)如果有就用使用者配置的,如果沒有,才自動配置;如果有些元件可以有多個(ViewResolver)將使用者配置的和自己預設的組合起來;

​ 2)、在SpringBoot中會有非常多的xxxConfigurer幫助我們進行擴充套件配置

​ 3)、在SpringBoot中會有很多的xxxCustomizer幫助我們進行定製配置