SpringBoot與Web開發


web開發
1)、創建SpringBoot應用,選中我們需要的模塊;
2)、SpringBoot已經默認將這些場景已經配置好了,只需要在配置文件中指定少量配置就可以運行起來
3)、自己編寫業務代碼;

自動配置原理?
這個場景SpringBoot幫我們配置了掃碼?能不能修改?能不能改哪些配置?能不能擴展?xxx
xxxAutoConfiguration:幫我們給容器中自動配置組件;
xxxProperties:配置類來 封裝配置文件的內容;

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

@ConfigurationProperties(prefix="spring.resources",ignoreUnknownFields=false)
public class ResourceProperties implements ResourceLoaderAware{

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

 1 public void addResourceHandlers(ResourceHandlerRegistry registry) {
 2     if (!this.resourceProperties.isAddMappings()) {
 3         logger.debug("Default resource handling disabled");
 4     } else {
 5         Duration cachePeriod = this.resourceProperties.getCache().getPeriod();
 6         CacheControl cacheControl = this.resourceProperties.getCache().getCachecontrol().toHttpCacheControl();
 7         if (!registry.hasMappingForPattern("/webjars/**")) {
 8             this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{"/webjars/**"}).addResourceLocations(new String[]{"classpath:/META-INF/resources/webjars/"}).setCachePeriod(this.getSeconds(cachePeriod)).setCacheControl(cacheControl));
 9         }
10 
11         String staticPathPattern = this.mvcProperties.getStaticPathPattern();
12         if (!registry.hasMappingForPattern(staticPathPattern)) {
13             this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{staticPathPattern}).addResourceLocations(getResourceLocations(this.resourceProperties.getStaticLocations())).setCachePeriod(this.getSeconds(cachePeriod)).setCacheControl(cacheControl));
14         }
15 
16     }
17 }
addResourceHandlers

//配置歡迎頁的映射

 1 @Bean
 2 public WelcomePageHandlerMapping welcomePageHandlerMapping(ApplicationContext applicationContext) {
 3     return new WelcomePageHandlerMapping(new TemplateAvailabilityProviders(applicationContext), applicationContext, this.getWelcomePage(), this.mvcProperties.getStaticPathPattern());
 4 }
 5 
 6 @Configuration
 7 @ConditionalOnProperty(
 8     value = {"spring.mvc.favicon.enabled"},
 9     matchIfMissing = true
10 )
11 public static class FaviconConfiguration implements ResourceLoaderAware {
12     private final ResourceProperties resourceProperties;
13     private ResourceLoader resourceLoader;
14 
15     public FaviconConfiguration(ResourceProperties resourceProperties) {
16         this.resourceProperties = resourceProperties;
17     }
18 
19     public void setResourceLoader(ResourceLoader resourceLoader) {
20         this.resourceLoader = resourceLoader;
21     }
22 
23     @Bean
24     public SimpleUrlHandlerMapping faviconHandlerMapping() {
25         SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
26         mapping.setOrder(-2147483647);
27 //所有 **/favicon.ico
28         mapping.setUrlMap(Collections.singletonMap("**/favicon.ico", this.faviconRequestHandler()));
29         return mapping;
30     }
31 
32     @Bean
33     public ResourceHttpRequestHandler faviconRequestHandler() {
34         ResourceHttpRequestHandler requestHandler = new ResourceHttpRequestHandler();
35         requestHandler.setLocations(this.resolveFaviconLocations());
36         return requestHandler;
37     }
配置歡迎頁的映射

//配置喜歡的圖標

    private List<Resource> resolveFaviconLocations() {
        String[] staticLocations = WebMvcAutoConfiguration.WebMvcAutoConfigurationAdapter.getResourceLocations(this.resourceProperties.getStaticLocations());
        List<Resource> locations = new ArrayList(staticLocations.length + 1);
        Stream var10000 = Arrays.stream(staticLocations);
        ResourceLoader var10001 = this.resourceLoader;
        this.resourceLoader.getClass();
        var10000.map(var10001::getResource).forEach(locations::add);
        locations.add(new ClassPathResource("/"));
        return Collections.unmodifiableList(locations);
    }
}
配置喜歡的圖標

1)、所有/webjars/**,都去classpath:/META-INF/resources/webjars/
找資源;
webjars:以jar包的 方式引入靜態資源;
參考:http://www.webjars.org/
http://localhost:8080/webjars/jquery/3.3.1-1/jquery.js

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

2)、"/**"訪問當前項目的任何資源,(靜態資源的文件夾)

"classpath:/META-INF/resources/",
"classpath:/resources/",
"classpath:/static/",
"classpath:/public/"
"/":當前項目的根路徑;
localhsot: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>
</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使用方法
只要我們把html頁面放在classpath:/templates/,thymeleaf就能自動渲染;
使用:
1、導入thymleaf的名稱空間;

<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屬性;來替換原生屬性的值;
參考官方文檔:https://www.thymeleaf.org/documentation.html pdf
2)、表達式?
4 Standard Expression Syntax
We will take a small break in the development of our grocery virtual store to learn about one of the most important
parts of the Thymeleaf Standard Dialect: the Thymeleaf Standard Expression syntax.
We have already seen two types of valid attribute values expressed in this syntax: message and variable expressions:
<p th:utext="#{home.welcome}">Welcome to our grocery store!</p>
<p>Today is: <span th:text="${today}">13 february 2011</span></p>
But there are more types of expressions, and more interesting details to learn about the ones we already know. First,
let’s see a quick summary of the Standard Expression features:
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.

${param.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自動配置
Spring Boot 自動配置好了SpringMVC
以下是SpringBoot對SpringMVC的默認配置:
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).ffavicon.ico;
自動注冊了 of Converter, GenericConverter, Formatter beans.
Convert:轉換器,public String hello(User user):類型轉換使用Convert
Formatter:格式化器;2017-12-17===Date;
自己添加的格式化器轉換器,我們只需要放在容器中即可;
Support for HttpMessageConverters (see below)
HttpMessageConverters :SpringMVC用來轉換Http請求和響應的;User--json;
HttpMessageConverters 是從容器中確定的;獲取所有的 HttpMessageConverters ;
只需要自己將自己的組件注冊在容器中;(@Bean、@component)
Automatic registration of MessageCodesResolver (see below).定義錯誤代碼生成 規則;
Automatic use of a ConfigurableWebBindingInitializer bean (see below).我們可以配置一個ConfigurableWebBindingInitializer 來替換默認的;(添加到容器)
1、初始化WebDataBinder;
2、請求數據====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

/**
 * Created by windMan on 2018/5/28
 */
//使用WebMvcConfigurerAdapter可以來擴展SpringMVC功能
@Configuration
public class MyMvcConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
//        super.addViewControllers(registry);
            //瀏覽器發送portalkjt請求到success
            registry.addViewController("/portalkjt").setViewName("success");
    }
}

原理:
1)、WebMvcAutoConfiguration 是SpringMvc的配置類;
2)、在做其他自動配置時會導入;@Import({WebMvcAutoConfiguration.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);
//一個參考實現;將所有的WebMvcConfigurater相關配置都來一起調用;
@Override
//public void addViewControllers(ViewControllerRegistry registry) {
//   for (WebMvcConfigurer delegate : this.delegates) {
//      delegate.addViewControllers(registry);
//   }
//}
   }
}

3)、容器中所有的WebMvcConfigurater都會一起起作用;
4)、我們的配置類也會被調用;
效果:SpringMVC的自動配置和我們的擴展配置都會起作用;
3、全面接管SpringMVC;
SpringBoot對SpringMVC的自動配置不需要了,所有都是我們自己配置;所有的SpringMVC的自動配置都失效了;
我們需要在 配置類中添加@EnableWebMvc即可;

/**
 * Created by windMan on 2018/5/28
 */
//使用WebMvcConfigurerAdapter可以來擴展SpringMVC功能

@EnableWebMvc
@Configuration
public class MyMvcConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
//        super.addViewControllers(registry);
            //瀏覽器發送portalkjt請求到success
            registry.addViewController("/portalkjt").setViewName("success");
    }
}

原理:
為什么添加@EnableWebMvc自動配置就失效了;
1)、@EnableWebMvc的核心

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

2)、

@Configuration
public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport {

3)、

@Configuration
@ConditionalOnWebApplication(
    type = Type.SERVLET
)
@ConditionalOnClass({Servlet.class, DispatcherServlet.class, WebMvcConfigurer.class})
//容器中沒有這個組件的時候,這個自動配置類才生效
@ConditionalOnMissingBean({WebMvcConfigurationSupport.class})
@AutoConfigureOrder(-2147483638)
@AutoConfigureAfter({DispatcherServletAutoConfiguration.class, ValidationAutoConfiguration.class})
public class WebMvcAutoConfiguration {

4)、@EnableWebMvc將WebMvcConfigurationSupport組件導入進來;

5)、導入的WebMvcConfigurationSupport只是SpringMVC最基本的功能;
5、如何修改SpringBoot的默認配置
1)、SpringBoot在自動配置很多組件的時候,先看容器中有沒有用戶自己配置的(@Bean、@Component)如果 有就 用用戶配置的,如果沒有,才自動配置;如果有些組件可以有多個(ViewResolver)將用戶配置的 和自己默認的組合起來;
2)、在SpringBoot中,會有非常多的xxConfigurater幫助我們進行擴展配置;

6、RestfulCRUD
1)、默認訪問首頁;
2)、國際化
1)、編寫國際化配置文件;
2)、使用ResourceBundleMessageSource管理國際化資源文件
3)、在頁面使用fmt:message取出國際化內容


步驟:
1)、編寫國際化配置文件、抽取頁面需要顯示的國際化消息;
2)、SpringBoot自動配置好了管理國際化資源文件的組件;

@Bean
@ConfigurationProperties(prefix = "spring.messages")
public MessageSourceProperties messageSourceProperties() 
String basename = context.getEnvironment().getProperty("spring.messages.basename", "messages");//我們的配置文件可以直接放在類路徑下叫message.properties;

@Bean
public MessageSource messageSource() {
    MessageSourceProperties properties = this.messageSourceProperties();
    ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
    if (StringUtils.hasText(properties.getBasename())) {
//設置國際化資源文件的基礎名(去掉語言國家代碼的) 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;
}
View Code

3)、去頁面獲取國際化的值;
file-encording 文件及編碼,根據當前瀏覽器語言設置的信息,切換的國際化;

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

@Bean
@ConditionalOnMissingBean
@ConditionalOnProperty(
    prefix = "spring.mvc",
    name = {"locale"}
)
public LocaleResolver localeResolver() {
    if (this.mvcProperties.getLocaleResolver() == org.springframework.boot.autoconfigure.web.servlet.WebMvcProperties.LocaleResolver.FIXED) {
        return new FixedLocaleResolver(this.mvcProperties.getLocale());
    } else {
        AcceptHeaderLocaleResolver localeResolver = new AcceptHeaderLocaleResolver();
        localeResolver.setDefaultLocale(this.mvcProperties.getLocale());
        return localeResolver;
    }
}
View Code

默認的就是根據請求頭帶來的區域信息獲取Locale進行國際化;
4)、點擊鏈接切換國際化;

/**
 * Created by windMan on 2018/5/28
 * 可以在鏈接上攜帶區域信息
 */
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 Local(split[0],split[1]);
        }
        return locale;
    }

    @Override
    public void setLocale(HttpServletRequest request, @Nullable HttpServletResponse response, @Nullable Locale locale) {

    }
}


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

3)、登錄
開發期間模版引擎頁面修改后,要實時生效;
1)、禁用模版引擎的緩存
#禁用緩存
spring.thymeleaf.cache=false
2)、頁面修改完成后ctrl+f9:重新編輯;
登錄錯誤消息的 顯示;

3)、攔截器進行登錄檢查

 //注冊攔截器
            @Override
            public void addInterceptors(InterceptorRegistry registry) {
//                super.addInterceptors(registry);
                    //靜態資源:*.css ,*.js
                    //SpringBoot已經 做好了靜態資源的映射
                    registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/**")
                            .excludePathPatterns("index.html","/","user/login");
            }

5)、CRUD-員工列表
實驗要求:
1)、RestfulCRUD:CRUD滿足Rest風格;
URI:/資源名稱/資源標識 HTTP請求方式區分對資源CRUD操作

2)、實驗的請求架構;

3)、員工列表
thymeleaf公共頁面元素抽取
1、抽取公共片段

<div th:fragment="copy">
&copy; 2011 The Good Thymes Virtual Grocery
</div>

2、引入公共片段

<div th:insert="~{footer :: copy}"></div>
~{templatename::selector}:模版名::選擇器
~{templatename::fragmentname}:模版名::片段名

3、默認效果:

insert的公共片段在div標簽中
如果使用th:insert等屬性進行引入,可以不用寫~{}:
行內寫法可以加上====[[]]:[~()]
三種引入公共片段的th屬性;
th:insert:將公共片段整個插入到聲明引入元素中;
th:replace:將聲明引入的元素替換為公共片段;
th:include:將被引入的片段的內容包含進這個標簽中;
<footer th:fragment="copy">
&copy; 2011 The Good Thymes Virtual Grocery
</footer>
引入方式:
<div th:insert="footer :: copy"></div>
<div th:replace="footer :: copy"></div>
<div th:include="footer :: copy"></div>

效果:
<div>
<footer>
&copy; 2011 The Good Thymes Virtual Grocery
</footer>
</div>

<footer>
&copy; 2011 The Good Thymes Virtual Grocery
</footer>

<div>
&copy; 2011 The Good Thymes Virtual Grocery
</div>

引入片段的時候傳入參數:
<div th:replace="::frag (onevar=${value1},twovar=${value2})">
${#dates.format(date, 'dd/MMM/yyyy HH:mm')}


日期的格式化;SpringMVC將頁面提交的值需要轉換為指定的類型; 類型轉換,格式化; 默認日期是按照/的方式;


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM