SpringBoot学习笔记

SpringBoot

第一章

  • 为什么要使用SpringBoot
    • 因为Spring,SpringMVC需要使用大量的配置文件(xml文件)。
    • 还需要配置各种对象,把使用的对象放入到spring容器中才能使用对象。
    • 需要了解其他框架配置规则。
  • SpringBoot就相当于不需要配置文件的spring+SpringMVC,常用的框架和第三方库都已经配置好了,拿来就可以用。
  • SpringBoot开发效率高,使用方便多了。

1.1 JavaConfig

  • JavaConfig:使用Java类作为xml配置文件的替代,是配置Spring容器的纯java的方式,在这个java类中可以创建java对象,把对象放入spring容器(注入到容器)。

  • 使用两个注解:

    • @Configuration:放在一个类的上面,表示这个类是作为配置文件使用的。
    • @Bean:声明对象,把对象注入到容器中。
  • import com.bjpowernode.vo.Student;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    
    /**
     * Configuration:表示当前类是作为配置文件使用的,就是用来配置容器的
     *  位置:在类的上面
     *
     *  SpringConfig这个类就相当于beans.xml
     */
    
    @Configuration
    public class SpringConfig {
    
        /**
         * 创建方法,方法的返回值是对象,在方法的上面加入@Bean
         * 方法的返回值对象就注入到容器中
         * @Bean:把对象注入到spring容器中,作用相当于<bena></bean>
         *  位置:方法的上面
         *
         *  说明:@Bean,不指定对象的名称,默认是方法名
         */
    
        @Bean
        public Student createStudent(){
            Student s1 = new Student();
            s1.setName("张三");
            s1.setAge(25);
            s1.setSex("男");
            return s1;
        }
    
        /**
         *
         * 指定对象的名称
         */
        @Bean(name = "lisiStudent")
        public Student Student1(){
            Student s2 = new Student();
            s2.setName("李四");
            s2.setAge(21);
            s2.setSex("男");
            return s2;
        }
    }
    
    

1.2 @ImportResource

  • @ImportResource 作用:导入其他配置文件,等于xml

  • <import resources = "其他配置文件"/>
    
  • @Configuration
    @ImportResource(value = "classpath:applicationContext.xml")
    public class SpringConfig {
    }
    

1.3 @PropertySource

  • @PropertySource:读取properties属性配置文件,使用属性配置文件可以实现外部化配置,在程序代码之外提供数据

  • 步骤:

    • 在resources目录下,创建properties文件,使用key=value的格式提供数据
    • 在@PropertySource指定properties文件的位置
    • 使用@Value(Value=“${key}”)
  • @Configuration
    @ImportResource(value = "classpath:applicationContext.xml")
    @ComponentScan(basePackages = "com.bjpowernode.vo")
    @PropertySource(value = "classpath:tiger.properties")
    public class SpringConfig {
    }
    

第二章 Spring Boot

2.1 介绍

  • SpringBoot是Spring中的一个成员,可以简化Spring,SpringMVC的使用,他的核心还是IOC容器
  • 特点:
    • 创建Spring应用
    • 内嵌的tomcat,jetty,Undertow
    • 提供了starter起步依赖,简化应用的配置。
      • 比如使用MyBatis框架,需要在Spring项目中,配置MyBatis的对象SqlSessionFactory,DAO的代理对象。
      • 在SpringBoot项目中,在pom.xml里面,加入一个mybatis-spring-boot-starter 依赖
    • 尽可能去配置spring和第三方库,叫做自动配置(就是把spring中的,第三方库中的对象都创建好,放到容器中,开发人员可以直接使用)
    • 提供了健康检查,统计,外部化配置
    • 不用生成代码,不用使用xml做配置

2.2 创建SpringBoot项目

2.2.1 第一种方式,使用Spring提供的初始化器,就是向导创建SpringBoot应用

  • 使用的地址:https://start.spring.io

2.2.2 第二种方式,使用国内的地址

  • 使用的地址:https://start.springboot.io

2.3 注解的使用

@SpringBootApplication
复合注解:
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan


1@SpringBootConfiguration

@Configuration
public @interface SpringBootConfiguration {
    @AliasFor(
        annotation = Configuration.class
    )
    boolean proxyBeanMethods() default true;
}
说明:使用了@SpringBootConfiguration注解标注的类,可以作为配置文件使用,可以使用Bean声明对象,注入到容器。

2@EnableAutoConfiguration
启用自动配置,把java对象配置好,注入到spring容器中。
例如可以把MyBatis的对象配置好,放到容器中
    
3@ComponentScan
扫描器,找到注解,根据注解的功能创建对象,给对象赋值等
默认扫描的包:@ComponentScan所在的类所在的包和子包

2.4 SpringBoot的配置文件

  • 配置文件名称:application

  • 拓展名有:properties(k=v) ; yml( k: v)

  • 使用application.properties(默认采用该文件)、application.yml

  • 例1:applicaiton.properties设置端口和上下文

  • #设置端口号
    server.port=8082
    #设置访问应用的上下文路径,contextPath
    server.servlet.context-path=/myboot
    
    
  • 例2:application.yml

  • server:
      port: 8083
      servlet:
        context-path: /myboot2
    
    

2.5 多环境配置

  • 有开发环境、测试环境、上线环境
  • 每个环境有不同的配置信息,例如端口,上下文,数据库url,用户名,密码等
  • 使用多环境配置文件,可以方便的切换不同的配置
  • 使用方式:创建多个配置文件,名称规则:applicaiton-环境名称.properties(yml)
    • 创建开发环境的配置文件:application-dev.properties(application-dev.yml)
    • 创建测试者使用的配置:application-test.properties(application-test.yml)

2.6

2.7 使用JSP

  • SpringBoot不推荐使用jsp,而是使用模板技术代替jsp
  • 使用jsp需要配置
    • 加入一个处理jsp的依赖。负责编译jsp文件
    • 如果需要使用servlet,jsp,jstl 加入依赖
    • 创建一个存放jsp的目录,一般叫做webapp
    • 需要在pom.xml指定jsp文件编译后的存放目录
    • 创建Controller,访问jsp
    • 在application.properties文件中配置视图解析器

2.8 使用容器

  • 想通过代码从容器中获取对象

  • 通过SpringApplication.run(Application.class,args); 返回值获取容器

  • public static ConfigurableApplicationContext run(Class<?> primarySource, String... args) {
            return run(new Class[]{primarySource}, args);
        }
    ConfigurableApplicationContext :接口,是ApplicationContext的子接口
    

2.9 CommandLineRunner接口,ApplicationRunner接口

  • 这两个接口都有一个run方法。执行时间在容器对象创建好后,自动执行run()方法

  • 可以完成自定义的在容器对象创建好的一些操作

  • @FunctionalInterface
    public interface CommandLineRunner {
        void run(String... args) throws Exception;
    }
    
    @FunctionalInterface
    public interface ApplicationRunner {
        void run(ApplicationArguments args) throws Exception;
    }
    
    

第三章 Web组件

3.1 拦截器

  • 拦截器是SpringMVC中的一种对象,能拦截对Controller的请求

  • 拦截器框架中有系统的拦截器,还可以自定义拦截器,实现对请求的预先处理

  • 实现自定义拦截器:

    • 创建类实现SpringMVC框架的HandlerInterceptor接口

    • public interface HandlerInterceptor {
          default boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
              return true;
          }
      
          default void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
          }
      
          default void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
          }
      }
      
    • 需在SpringMVC的配置文件中声明拦截器

    • <mvc:interceptors>
      	<mvc:interceptor>
          	<mvc:path="url"/>
              <bean class="拦截器全限定名称"/>
          </mvc:interceptor>
      </mvc:interceptors>
      
  • SpringBoot中注册拦截器:

  • @Configuration
    public class Config implements WebMvcConfigurer {
    
        //添加拦截器对象,注入到容器中
        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            //创建拦截器对象
            HandlerInterceptor interceptor = new LoginInterceptor();
    
            //指定拦截的请求uri地址
            String path[] = {"/user/**"};
            //指定不拦截的地址
            String excludepath[] = {"/user/login"};
    
            registry.addInterceptor(interceptor)
                    .addPathPatterns(path)
                    .excludePathPatterns(excludepath);
        }
    }
    

Servlet

  • 在SpringBoot框架中使用Servlet对象

  • 使用步骤:

    • 创建Servlet类,创建类继承HttpServlet
    • 注册Servlet,让框架能找到Servlet
  • 例子:

    • 创建自定义Servlet

      public class MyServlet extends HttpServlet {
          @Override
          protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
              doPost(req,resp);
          }
      
          @Override
          protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
              response.setContentType("text/html;charset=UTF-8");
              PrintWriter out = response.getWriter();
              out.print("servlet11111111111");
          }
      }
      
    • 注册Serlvet

      @Configuration
      public class MyConfig {
      
          @Bean
          public ServletRegistrationBean servletRegistrationBean(){
              /*ServletRegistrationBean bean =
                      new ServletRegistrationBean(new MyServlet(),"/myservlet");
              */
      
              ServletRegistrationBean bean = new ServletRegistrationBean();
              bean.setServlet(new MyServlet());
              bean.addUrlMappings("/myservlet","/zzq");
              return bean;
          }
      }
      

3.3 过滤器Filter

  • Filter是Servlet规范中的过滤器,可以处理请求,对请求的参数,属性进行调整。常常在过滤器中处理字符编码。

  • 在框架中使用过滤器:

    • 创建自定义过滤器类
    • 注册Filter过滤器对象
  • 例子:

    • public class Filter implements javax.servlet.Filter {
          @Override
          public void doFilter(ServletRequest servletRequest,
                               ServletResponse servletResponse,
                               FilterChain filterChain) throws IOException, ServletException {
              System.out.println("过滤器执行");
              filterChain.doFilter(servletRequest,servletResponse);
      
          }
      }
      
    • 注册Filter

      @Configuration
      public class MyConfig {
      
          @Bean
          public FilterRegistrationBean filterRegistrationBean(){
              FilterRegistrationBean bean = new FilterRegistrationBean();
              bean.setFilter(new Filter());
              bean.addUrlPatterns("/user/*");
              return bean;
          }
      }
      

3.4 字符集过滤器

  • CharacterEncodingFilter:解决post请求中乱码的问题

  • 在SpringMVC框架,在web.xml注册过滤器,配置属性

    第一种方式:

  • 使用步骤:

    • 配置字符集过滤器

      
      @Configuration
      public class MyConfig {
      
          @Bean
          public ServletRegistrationBean servletRegistrationBean(){
              ServletRegistrationBean bean = new ServletRegistrationBean();
              bean.setServlet(new MyServlet());
              bean.addUrlMappings("/myservlet");
              return bean;
          }
      
          @Bean
          public FilterRegistrationBean filterRegistrationBean(){
              FilterRegistrationBean bean = new FilterRegistrationBean();
      
              CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
              characterEncodingFilter.setEncoding("utf-8");
              characterEncodingFilter.setForceEncoding(true);
              bean.setFilter(characterEncodingFilter);
              bean.addUrlPatterns("/*");
              return bean;
          }
      }
      
    • 修改application.properties文件,让自定义的过滤器起作用

      #SpringBoot中默认已经配置CharacterEncodingFilter,编码默认是ISO-8859-1
      #设置enabled=false 作用是关闭系统中配置好的过滤器,使用自定义的CharacterEncodingFilter
      server.servlet.encoding.enabled=false
      

​ 第二种方式

  • 修改application.properties文件

    #让系统的CharacterEncodingFilter生效(可省略)
    server.servlet.encoding.enabled=true
    #指定使用的编码方式
    server.servlet.encoding.charset=UTF-8
    #强制request response都是用charset属性的值
    server.servlet.encoding.force=true
    

第四章 ORM操作MySQL

  • 使用MyBatis框架操作数据,在SpringBoot框架继承MyBatis
  • 使用步骤:
    • MyBatis起步依赖:完成MyBatis对象自动配置,对象放在容器中
    • 在pom.xml文件中指定src/main/java目录中的xml包含到classpath中
    • 创建实体类Student
    • 创建Dap接口StudentDao,创建一个查询学生的方法
    • 创建Dao接口对应的Mapper文件,xml文件,写sql语句
    • 创建Service层对象,创建StudentService接口和他的实现类,去调用dao对象的方法,完成数据库操作
    • 创建Controller对象,访问Service
    • 写application.properties文件,配置数据库连接信息

第一种方式

  • @Mapper:放在dao接口的上面,每个接口都需要使用这个注解

    @Mapper
    public interface StudentDao {
    
        Student selectById(@Param("stuId") Integer id);
    }
    

第二种方式

  • @MapperScan放在主启动类上

    @SpringBootApplication
    @MapperScan(basePackages = "com.bjpowernode.dao")
    public class Application {
    
        public static void main(String[] args) {
            SpringApplication.run(Application.class, args);
        }
    
    }
    

第三种方式

  • 先把Mapper文件放在resources目录下

    • 在resources目录中创建子目录(自定义),例如mapper

    • 把mapper文件放到mapper目录种

    • 在application.properties文件中,指定mapper文件的目录

      #指定mapper位置
      mybatis.mapper-locations=classpath:mapper/*.xml
      
      #日志
      mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
      
    • 在pom.xml中指定把resources目录中的文件,编译到目标目录中

      <!--resources插件-->
              <resources>
                  <resource>
                      <directory>src/main/java</directory>
                      <includes>
                          <include>**/*.xml</include>
                      </includes>
                  </resource>
                  <resource>
                      <directory>src/main/resources</directory>
                      <includes>
                          <include>**/*.*</include>
                      </includes>
                  </resource>
              </resources>
      

事务

  • Spring框架中的事务
    • 管理事务的对象:事务管理器(接口,接口有很多实现类)
      • 例如:使用jdbc或mybatis访问数据库,使用的事务管理器:DataSourceTransactionManager
    • 声明式事务:在xml配置文件或者使用注解说明事务控制的内容
      • 控制事务:隔离级别、传播行为、超时时间
    • 事务处理方式:
      • Spring框架中的@Transactional
      • aspectJ框架可以在xml配置文件中,声明事务控制的内容
  • SpringBoot中的事务:上面的两种方式都可以
    • 在业务方法的上面加入@Transactional注解,加入注解后,方法就有事务功能了
    • 明确的在 主启动类的上面,加入@EnableTransactionManagement 注解

第五章 接口架构风格 -RESTful

  • 接口:API(Application Programming Interface,应用程序接口)是一些预先定义的接口(如函数、HTTP接口),或指软件系统不同组成部分衔接的约定。用来提供应用程序与开发人员基于某软件或硬件得以访问的一组例程,而又无需访问源码,或理解内部工作机制的细节。

  • 接口(API):可以指访问servlet、controller的url,调用其他程序的函数

  • 架构风格:API组织方式(样子)

    • 就是一个传统的:http://localhost:8080/mytrans/addStudent?name=1
    • 在地址上提供了访问的资源名称addStudent,在其后使用了get方式传递参数

    5.1 RESTful架构风格

  • REST:(Representational State Transfer,中文:表现层状态转移)

    • REST:是一种接口的架构风格的设计的理念,不是标准。
    • 优点:更简洁,更有层次
  • REST中的要素:

    • 用REST表示资源和对资源的操作。在互联网中,表示一个资源,或者一个操作。
    • 资源使用url表示的,在互联网,使用的图片,视频,文本,网页等等都是资源。
    • 资源是用名词表示。
  • 一句话说明REST:

    • 使用url表示资源,使用http动作操作资源。
  • 注解:

    • @PathVariable:从url中获取数据
    • GetMapping:支持的get请求方式,等同于@RequestMapping(method=RequestMethod.GET)
    • PostMapping:支持post请求方式,等同于@RequestMapping(method=RequestMethod.POST)
    • PutMapping:支持put请求方式,等同于@RequestMapping(method=RequestMethod.PUT)
    • DeleteMapping:支持delete请求方式,等同于@RequestMapping(method=RequestMethod.DELETE)
    • RestController:复合注解,是@ResponseBody和@Controller组合
      • 在类的上面使用@RestController,表示当前类的所有方法都加了@ResponseBody

5.2 在页面中或者ajax中,支持put,delete请求

  • 在SpringMVC中有一个过滤器,支持post请求转为put、delete
  • 过滤器:org.springframework.web.filter.HiddenHttpMethodFilter
  • 作用:把请求中的post请求转为put、delete
  • 实现步骤:
    • application.properties(yml):开启使用HiddenHttpMethodFilter 过滤器
    • 在请求页面中,包含_method参数,它的值是put、delete,发起这个请求使用的post方式

第六章 Redis

  • Redis:一个NoSQL数据库,常用作 缓存(Cache) 使用
  • Redis的数据类型:string、hash、set、zset、list
  • Redis是一个中间件:是一个独立的服务器
  • java中著名的客户端:Jedis、lettuce、Redisson
  • Spring,SpringBoot中有一个RedisTemplate(StringRedisTemplate),处理和redis交互

6.1 配置Windows版本的Redis

  • redis-server.exe:服务端,启动后不要关闭

  • redis-cli.exe:客户端,访问redis中的数据

  • RedisTemplate 使用的是 lettuce客户端库

  • 可以在application.properties里面配置redis的信息

    • #指定redis (host、ip、password)
      spring.redis.host=localhost
      spring.redis.port=6379
      spring.redis.password=123
      

6.2 对比StringRedisTemplate和RedisTemplate

  • StringRedisTemplate:把K,V都是作为String处理,使用的是String的序列化,可读性好

  • RedisTemplate:把K,V经过了序列化存到redis,K,V是序列化的内容,不能直接识别,默认使用的jdk序列化。

  • 为什么要序列化?

    • 序列化最终的目的是为了对象可以跨平台存储和进行网络传输,而我们进行跨平台存储和网络传输的方式就是IO,而我们的IO支持的数据格式就是字节数组。我们必须在把对象转换成字节数组的时候指定一种规则(序列化),那么我们从IO流里面读出数据的时候再以这种规则把对象还原回来(反序列化)。
  • 什么情况下需要序列化?

    • 通过上面已经知道了凡是需要跨平台存储和网络传输的都需要序列化。
    • 本质上存储和网络传输都需要经过把一个对象状态保存成一种跨平台识别的字节格式,然后其他平台才可用通过字节信息解析还原对象信息。
  • 序列化的方式:

    • 序列化只是一种拆箱组装对象的规则,那么这种规则肯定会有多种多样,比如现在常见的序列化方式有:JDK(不支持跨语言)、JSON、XML、Hessian、Kryo(不支持跨语言、Thrift、Protofbuff)
    • Student(name=zhangsan,age=20) ------- {“name”:“zhangsan”,“age”:20}
  • java的序列化:把java对象转换成byte[],二进制数据

  • json序列化:json序列化功能将对象转换为JSON格式或从JSON格式转换对象。例如把一个Student对象转换成JSON字符串{“name”:“李四”,“age”:29},反序列化将JSON字符串转换为Student对象

  • 设置key或者value的序列化方式:

    //使用RedisTemplate,在存取值之前,设置序列化
    //设置key使用String的序列化
    redisTemplate.setKeySerializer(new StringRedisSerializer());
    
    //设置value使用String的序列化
    redisTemplate.setValueSerializer(new StringRedisSerializer());
    
    redisTemplate.opsForValue().set(k)
    

第七章 SpringBoot继承Dubbo

7.1 看Spring Boot继承Dubbo的文档

https://github.com/apache/dubbo-spring-boot-project/blob/master/README_CN.md

7.2 公共项目

  • 独立的maven项目:定义了接口和数据类

    public class Student implements Serializable {
    
        private Integer id;
        private String name;
        private Integer age;
    }
    
    public interface StudentService {
    
        Student queryStudentById(Integer id);
    }
    

7.3 提供者

  • 创建SpringBoot项目

  • pom.xml

    <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter</artifactId>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>
    
            <!--公共接口-->
            <dependency>
                <groupId>org.example</groupId>
                <artifactId>022_interface_api</artifactId>
                <version>1.0-SNAPSHOT</version>
            </dependency>
    
    
            <!--dubbo-->
            <dependency>
                <groupId>org.apache.dubbo</groupId>
                <artifactId>dubbo-spring-boot-starter</artifactId>
                <version>2.7.8</version>
            </dependency>
    
            <!--zookeeper-->
            <dependency>
                <groupId>org.apache.dubbo</groupId>
                <artifactId>dubbo-dependencies-zookeeper</artifactId>
                <version>2.7.8</version>
                <type>pom</type>
                <!--排除依赖 重复了-->
                <exclusions>
                    <exclusion>
                        <groupId>slf4j-log4j12</groupId>
                        <artifactId>org.slf4j</artifactId>
                    </exclusion>
                </exclusions>
            </dependency>
        </dependencies>
    
  • 实现接口

    @DubboService(interfaceClass = StudentService.class,version = "1.0.0")
    public class StudentServiceImpl implements StudentService {
    
        @Override
        public Student queryStudentById(Integer id) {
            Student student = new Student();
            if(1001 == id){
                student.setId(1001);
                student.setName("1001-张三");
                student.setAge(20);
            }else if(1002 == id){
                student.setId(1002);
                student.setName("1002-lisi");
                student.setAge(22);
            }
            return student;
        }
    }
    
  • 修改application.properties配置

    #配置服务名称
    spring.application.name=studentservice-provider
    
    #扫描包
    dubbo.scan.base-packages=com.bjpowernode.service
    
    #注册中心
    dubbo.registry.address=zookeeper://localhost:2181
    
  • 在启动类上面加@EnableDubbo注解

    @SpringBootApplication
    @EnableDubbo
    public class Application {
    
        public static void main(String[] args) {
            SpringApplication.run(Application.class, args);
        }
    }
    

7.4 消费者

  • 创建SpringBoot项目

  • pom.xml

    <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter</artifactId>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>
    
            <!--公共接口-->
            <dependency>
                <groupId>org.example</groupId>
                <artifactId>022_interface_api</artifactId>
                <version>1.0-SNAPSHOT</version>
            </dependency>
    
    
            <!--dubbo-->
            <dependency>
                <groupId>org.apache.dubbo</groupId>
                <artifactId>dubbo-spring-boot-starter</artifactId>
                <version>2.7.8</version>
            </dependency>
    
            <!--zookeeper-->
            <dependency>
                <groupId>org.apache.dubbo</groupId>
                <artifactId>dubbo-dependencies-zookeeper</artifactId>
                <version>2.7.8</version>
                <type>pom</type>
                <!--排除依赖 重复了-->
                <exclusions>
                    <exclusion>
                        <groupId>slf4j-log4j12</groupId>
                        <artifactId>org.slf4j</artifactId>
                    </exclusion>
                </exclusions>
            </dependency>
        </dependencies>
    
  • 创建Controller或者Service都可以

    @RestController
    public class StudentController {
    
        @DubboReference(version = "1.0.0")
        private StudentService studentService;
    
        @GetMapping("/query")
        public String queryStudentById(Integer id){
            Student student = studentService.queryStudentById(id);
            return "student=" +student;
        }
    }
    
  • 修改application.properties

    spring.application.name=consumer-application
    
    dubbo.registry.address=zookeeper://localhost:2181
    
    

第八章 打包

打包为War

  • 创建了一个包含了jsp的项目

  • 修改pom.xml

    • 指定打包后的文件名称

      <build>
      
              <!--打包后文件名称-->
              <finalName>myboot</finalName>
      
    • 指定Jsp的编译目录

      <resources>
                  <!--resources插件,把jsp编译到指定目录-->
                  <resource>
                      <directory>src/main/webapp</directory>
                      <targetPath>META-INF/resources</targetPath>
                      <includes>
                          <include>**/*.*</include>
                      </includes>
                  </resource>
      
                  <!--使用mybatis,而且mapper文件在src/main/java目录下-->
                  <resource>
                      <directory>src/main/java</directory>
                      <includes>
                          <include>**/*.xml</include>
                      </includes>
                  </resource>
      
                  <!--把src/main/resources下面的所有文件都包含到classes目录中-->
                  <resource>
                      <directory>src/main/resources</directory>
                      <includes>
                          <include>**/*.*</include>
                      </includes>
                  </resource>
      
      
              </resources>
      
    • 执行打包为war

       <packaging>war</packaging>
      
    • 主启动类继承SpringBootServletInitializer(继承这个类,才能使用独立tomcat)

      @SpringBootApplication
      public class Application  extends SpringBootServletInitializer {
      
          public static void main(String[] args) {
              SpringApplication.run(Application.class, args);
          }
      
          @Override
          protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
              return builder.sources(Application.class);
          }
      }
      
      
    • 部署war

      • 把war放到tomcat等服务器的发布目录中,tomcat为例,把myboot.war放到tomcat/webapps目录下

打包为Jar

  • 跟war相似,不需要设定packaging,默认为jar
    • 也不需要继承SpringBootServletInitializer

War 和 Jar 比较

  • war包能充分利用服务器的处理能力,比如可以利用tomcat的能力处理请求和操作
  • jar包优势是小巧,可以独立运行,不需要依赖服务器,虽然内嵌tomcat但是怎么也比不上独立的tomcat

第九章 Thymeleaf模板引擎

  • Thymeleaf是一个流行的模板引擎,采用Java开发
  • 模板引擎是一个技术名词,是跨领域跨平台的概念,Java生态下的模板引擎有Thymeleaf、Freemaker、Velocity、Beetl(国产)等
  • Thymeleaf对网络环境不存在严格的要求,既能用于Web环境下,也能用于非Web环境下。在非Web环境下,他能直接显示模板上的静态数据,在Web环境下,他能像JSP一样从后台接收数据并替换掉模板上的静态数据。它是基于HTML的,以HTML标签为载体,Thymeleaf要寄托在HTML标签下实现。
  • SpringBoot继承了Thymeleaf模板技术,并且SpringBoot官方也推荐使用Thymeleaf来替代JSP技术,Thymeleaf是另外的一种模板技术,它本身并不属于SpringBoot,SpringBoot只是很好的集成这种模板技术,作为前端页面的展示,在过去的Web开发中,我们往往会使用JSP去完成页面的动态渲染,但是JSP需要翻译编译运行,效率低
  • Thymeleaf官网:
    • http://www.thymeleaf.org
  • Thymeleaf官方手册:
    • https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html

9.1 表达式

  • 标准变量表达式
    • 语法:${key}
    • 作用:获取key对应的文本数据
    • 在页面中的html标签中,使用th:test=“${key}”
  • 选择变量表达式(星号变量表达式)
    • 语法:*{key}
    • 作用:获取key对应的数据,*{key}需要和th:object 这个属性一起使用
    • 目的是简化获取对象的属性值
  • 链接表达式
    • 语法:@{url}
    • 作用:表示链接

9.2 Thymeleaf属性

  • 属性是放在HTML元素中的,就是html元素的属性,加入了th前缀,属性的作用不变,加上th,属性的值由模板引擎处理,在属性可以使用变量表达式

  • 例如

    • <form action="/loginServlet" method="post">
      </form>
      <from th:action="loginServlet" th:method="${methodAttr}">
      </from>
      

9.3 Each

  • Each循环,可以循环List,Array,Map

  • 语法:

    • 在一个HTML标签中,使用th:each

      <div th:each="集合循环成员,循环的状态变量:${key}">
          <p th:text="${集合循环成员}">
          </p>
      </div>
      
      集合循环成员,循环的状态变量:两个名称都是自定义的,“循环的状态变量”可以不定义,默认是“集合循环变量Stat”
      
    • each循环Map

    • <div th:each="集合循环成员,循环的状态变量:${key}">
          <p th:text="${集合循环成员.key}"></p>
          <p th:text="${集合循环成员.value}"></p>
      </div>
      
      集合循环成员,循环的状态变量:两个名称都是自定义的,“循环的状态变量”可以不定义,默认是“集合循环变量Stat”
      
      key:map集合中的key
      value:map集合中keydui
      

9.4 If

  • “th:if”:判断语句,当条件为true时,显示html标签体的内容,反之不显示,没有else语句

    语法:
    <div th:if="10 > 0">显示文本内容</div>
    
  • 还有一个th:unless 和 th:if相反的行为

    <div th:unless="10 < 0 ">当条件为false显示文本内容</div>
    

9.5 switch

  • th:switch和java中的一样

    语法:
    <div th:switch="要比对的值">
        <p th:case="值1">
            结果1
        </p>
        <p th:case="值2">
            结果2
        </p>
        <p th:case="*">
            默认结果
        </p>
        以上的case只有一个语句执行
    </div>
    

9.6 inline

  • 内联text:在html标签外,获取表达式的值

    • 语法:
    <div th:inline=“text”>
    	<p>我是[[${name}]]</p>
    </div>
    
  • 内联javascript

    • 语法:
    <script type="text/javascript" th:inline="javascript">
        var myname=[[${name}]];
        var myage=[[${age}]];
        
        function fun(){
            alert("获取数据" + myname+ ","+[])
        }
    </script>
    

9.7 字面量

9.8 字符串连接

  • 连接字符串有两种语法:

    • 语法使用 单引号括起来字符串 ,使用 + 连接其他的字符串或者表达式

      <p th:text="'我是' + ${name} + ',我所在城市' + ${city}">
          数据显示
      </p>
      
    • 使用双竖线,|字符串和表达式|

      <p th:text="|我是${name},我所在城市${city}|">数据显示
      </p>
      

9.9 运算符

9.10 内置对象

  • #request 表示HttpServletRequest
  • #session表示HttpSession对象
  • session表示Map对象,是#session的简单表示方式,作用是用来获取session中指定key的value
  • 这些是内置对象,可以在模板文件中直接使用

9.11 内置工具类

  • 内置工具类:Thymeleaf自己的一些类,提供对String,date,集合的一些处理方法
  • #datas:处理日期的工具类
  • #numbers:处理数字的
  • #lists:处理list集合的
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值