zoukankan      html  css  js  c++  java
  • spring boot 尚桂谷学习笔记04 ---Web开始

    ------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!orgspringframeworkoot

      autoconfigurewebservletWebMvcAutoConfiguration.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();
        }
    }
  • 相关阅读:
    【计算机视觉】OpenCV篇(2)
    【计算机视觉】OpenCV篇(1)
    傅立叶分析与小波分析整理
    极简Python DeBug工具——PySnooper
    透过SourceTree再谈Git
    佳文赏析:How to uninstall Linux
    AI佳作解读系列(四)——数据增强篇
    AI佳作解读系列(三)——深度学习中的合成数据研究
    java基础 序列化反序列化流 实现Serializable 接口 自动装载序列号到对象文本文件如修改不能反序列化对象文本,除非自定义long型常量 打印流
    java基础IO流 复制键盘录入的目录,复制其中的.java文件到指定目录,指定目录中有重名,则改名 对加密文件计算字母个数
  • 原文地址:https://www.cnblogs.com/lixuchun/p/8971680.html
Copyright © 2011-2022 走看看