SpringBoot及Thymeleaf快速入门

SpringBoot简化了Spring和SpringMVC的配置,提供自动配置和starter依赖。本文介绍了SpringBoot的创建、配置文件、多环境配置、@ConfigurationProperties、Web组件如拦截器、Servlet、Filter以及ORM操作数据库等方面,旨在帮助开发者快速上手SpringBoot。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.为什么使用SpringBoot

  • 因为Spring、SpringMVC的使用需要大量的配置文件,还要配置各种对象,将使用的对象放入Spring容器才能使用对象过于麻烦。
  • SpringBoot就相当于不需要配置文件的Spring+SpringMVC。常用的框架和第三方库都已经配置好了;拿来就可以使用了。
  • 使用方便、开发效率高

2.JavaConfig

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

使用到两个注解:

  1. @configuration:放在一个类的上面,表示这个类是作为配置文件使用的

  2. @Bean:声明对象,将对象注入到容器中

    @Configuration//当前类用做配置文件使用,配置容器
    public class SpringConfig {
    //    创建方法,方法的返回值是对象,方法上@Bean
    //    方法的返回值就注入到容器中了
        @Bean//将对象注入到spring容器中,相当于<bean>
    //    @Bean(name = "zsStu")指定名称id,不指定名称则默认是方法名
        public Student creatStudent(){
            Student student = new Student("张三",26,"男");
            return student;
        }
    }
    

    使用:

    ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
    Student student = (Student) ctx.getBean("creatStudent");//未指定id是方法名
    

3.@ImportResource

@ImportResource是导入xml配置,等同于xml文件的resource

//在配置类上添加该注释,导入xml文件配置,要带classes
@ImportResource(value = {"classes:beans.xml",..})

4.@PropertyResource

@PropertyResource是读取properties属性配置文件,实现外部化配置

  • resources目录下存放properties文件,k=v格式

  • @PropertyResource指定properties文件位置

  • 使用:@Value(value=“${key}”)

    @Configuration//当前类用做配置文件使用,配置容器
    @ImportResource(value = {"classes:beans.xml"})//xml导入
    @PropertySource(value = "classpath:config.properties")//properties文件读取
    @ComponentScan(basePackages = "jv.com.vo")//包扫描
    public class SpringConfig {..}
    //使用properties文件读取的数据tiger.name
    @value("${tiger.name}")String name;
    

5.什么是SpringBoot

​ SpringBoot是Spring家族中的一个成员,可以简化Spring、SpringMVC的使用。他的核心还是IOC容器。

​ 特点:

  1. 创建Spring应用
  2. 内嵌的Tomcat、jetty,undertow服务器
  3. 提供了starter起步依赖,简化应用的配置
  4. 尽可能去配置spring和第三方库,称为自动配置(spring和第三方的对象都创建好放入容器中,开发时可直接使用)
  5. 提供了健康检查、统计、外部化配置
  6. 无需生成代码、无需使用xml,做配置

6.创建SpringBoot项目

  1. 使用Spring提供的初始化器,向导创建SpringBoot应用
  2. 使用国内地址:https://start.springboot.io 快速构建springboot框架
  3. 使用普通maven项目

7.注解的使用

  • ​ @SpringBootApplication:是个复合注解,由以下三个注解组成

    1. @SpringBootConfiguration: //注解标注的类可当作配置文件使用,可用@Bean声明对象并注入到容器
    2. @EnableAutoConfiguration: //启用自动配置,把java对象配置好注入到spring容器中,例如可把mybatis对象创建好,放入容器中
    3. @ComponentScan://扫描器,找到注解根据注解的功能创建对象,给属性赋值等等;默认扫描的包:@ComponentScan所在的包和子包。

8.SpringBoot的配置文件

​ 配置文件名称:application

扩展名有:

  1. properties(k=v)

    #设置端口号
    server.port=8080
    #设置应用上下文路径 contextpath
    server.servlet.context-path=/myboot
    
  2. 和 yml(k:v)

    server:
      port: 8082
      servlet:
        context-path: /myboot2
    

9.多环境配置

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

10.@ConfigurationProperties读取配置文件

@ConfigurationProperties:读取配置文件中的数据交给一个java实体类,对其属性赋值。

@ConfigurationProperties(prefix = "school")

11.使用容器

想通过代码从容器中获取对象,可通过SpringApplication.run(Applicattion.class,args);返回值获取容器。

12.CommandLineRunner和ApplicationRunner接口

  • 这俩个接口都有一个run方法;执行时间是在容器对象创建好之后自动执行run()方法,可完成自定义的在容器对象创建好的一些操作。

13.Web组件——拦截器

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

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

  • Springmvc中自定义拦截器:

    1. 创建类去实现springmvc中的HandlerInterceptor接口,实现其中方法

    2. 声明拦截器

      <mvc:interceptors>
      	<mvc:interceptor>
          	<mvc:path="url"></mvc:path>
              <bean class="拦截器类全限定名"></bean>
          </mvc:interceptor>
      </mvc:interceptors>
      
  • 在springboot中自定义拦截器:

    • 创建类去实现springmvc中的HandlerInterceptor接口,实现其中方法
    • 配置类中实现WebMvcConfigurer接口实现addInterceptor方法
    @Configuration
    public class SpringConfig implements WebMvcConfigurer {
        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            LInterceptor interceptor = new LInterceptor();//拦截器
            registry.addInterceptor(interceptor)
                    .addPathPatterns("/user/**")
                    .excludePathPatterns("/user/login");
        }
    }
    

14.Web组件——Servlet

  1. 创建自定义Servlet类

    public class MyServlet extends HttpServlet {
        @Override
        protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            resp.setContentType("text/html;charset=utf-8");
            PrintWriter writer = resp.getWriter();
            writer.print("执行Servlet");
        }
    }
    
  2. 在配置类中注册Servlet

    @Configuration
    public class WebApplicationConfig {
        @Bean
        public ServletRegistrationBean servletRegistrationBean(){
            ServletRegistrationBean<Servlet> b = new ServletRegistrationBean<>();
            b.setServlet(new MyServlet());
            b.addUrlMappings("/test","/login");
            return b;
        }
    

15.Web组件——Filter过滤器

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

在框架中使用过滤器:

  1. 创建自定义过滤器类

    public class MyFilter implements Filter {
        @Override
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
            System.out.println("执行了MYFilter doFilter");
            filterChain.doFilter(servletRequest,servletResponse);
        }
    }
    
  2. 注册Filter过滤器对象

    @Bean
    public FilterRegistrationBean filterRegistrationBean(){
        FilterRegistrationBean<Filter> bean = new FilterRegistrationBean<>();
        bean.setFilter(new MyFilter());
        bean.addUrlPatterns("/user/*");
        return bean;
    }
    

16.字符集过滤器

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

  • 在MVC中,是在web.xml注册过滤器,配置属性。

  • 在Spring中默认配置了CharacterEncodiongFilter编码是ISO-8859-1,因此我们重新设置字符集的话就必须在application.yml核心配置中写上:server.servlet.encoding.enabled=false //关闭系统默认的过滤器,使用自定义的字符集过滤器

    第一种方式:

  • 步骤:

    配置类中注册设置字符集的Filter

    //配置类中注册设置字符集的Filter
    @Bean
    public FilterRegistrationBean filterCharacterRegistrationBean(){
        FilterRegistrationBean<Filter> bean = new FilterRegistrationBean<>();
        //使用框架中的Filter: CharacterEncodingFilter
        CharacterEncodingFilter filter = new CharacterEncodingFilter();
        filter.setEncoding("utf-8");//指定编码
        filter.setForceEncoding(true);// req、res都应用
        bean.setFilter(filter);
        bean.addUrlPatterns("/*");
        return bean;
    }
    

    修改application.properties核心配置,关闭系统默认的过滤器,使用自定义的字符集过滤器

    server.servlet.encoding.enabled=false
    

    第二种方式:直接在application.properties配置(推荐)

    #指定编码
    server.servlet.encoding.charset=utf-8  
    #req、res都应用
    server.servlet.encoding.force=true  
    

17.ORM(对象关系映射)操作数据库

  • 使用MyBatis框架操作数据库,在SpringBoot框架中集成的MyBatis

  • 步骤:

    1. mybatis起步依赖:完成MyBatis对象自动配置,对象放在容器中

    2. pom.xml文件中指定src/main/java目录中的xml文件包含到classpath中

    3. 创建实体类

    4. 创建Dao接口及对应的Mapper文件,写sql语句

    5. 创建Service层接口及实现类,需要拿到dao对象去调用方法完成数据库操作

    6. 创建Controller对象,访问Service

    7. 写application.properties文件,配置数据库

      server.port=9001
      server.servlet.context-path=/orm
      #连接数据库连接池,cj.的驱动版本更新
      spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
      spring.datasource.url=jdbc:mysql://localhost:3306/springdb?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8
      spring.datasource.username=root
      spring.datasource.password=hsp
      
  • 第一种方式:@Mapper

    放在dao接口上,每个接口都需要注解

    @Mapper//告诉MyBatis,这是dao接口,创建此接口的代理对象
    public interface StudentDao {
        Student queryById(@Param("stuId") Integer id);
    }
    
  • 第二种方式:@MapperScan扫描

    在SpringBootApplication类上添加@MapperScan

    /**
     * @MapperScan :找到Dao接口和mapper.xml文件
     *        basePackages:dao接口所在的包名
     */
    @SpringBootApplication
    @MapperScan(basePackages = "com.jv.dao")
    public class Application {
       public static void main(String[] args) {
          SpringApplication.run(Application.class, args);
       }
    }
    
  • 第三种方式:可将Dao接口和Mapper文件分开

    1. 在resource资源目录下新建目录mapper(自定义)用来保存XXDao.xml文件

    2. 在application.properties中指定mapper文件的目录:(编译后会放到target的classes文件中,所以用关键字classpath指定文件目录)

      #指定mapper文件位置
      mybatis.mapper-locations=classpath:mapper/*.xml
      
    3. pom中将src/main/resources的文件都放到target文件中

      <build>
      <!--      resources插件-->
            <resources>
               <resource>
                  <directory>src/main/resources</directory>
                  <includes>
                     <include>**/*.*</include>
                  </includes>
               </resource>
            </resources>
      </build>b
      
    4. 开启日志只需要在application.properties中配置(和之前在SqlMapperConfig.xml中的配置一样):

      #指定MyBatis的日志
      mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
      

18.@Repository和@Mapper的区别

  • @Repository和@Mapper注解都是用在dao层上的注解,标记为持久层;不过使用上也会有区别@Repository是spring的注解,标记为一个bean,配合mybatis时需要配置@MapperScan扫描.
  • @Mapper是mybatis的注解,不需要额外的@MapperScan扫描.
  • 使用@Repository后才能使用@Autowired自动装配,@Mapper用@Resource来装配。

19.@Resource和@Autowired的区别

  • @Resource的作用相当于@Autowired;
  • @Autowired按byType自动注入,而@Resource默认按 byName自动注入罢了;
  • @Resource是JDK自带的注解,而@Autowired是Spring提供的注解;
  • @Resource有两个属性是比较重要的,分是name和type,Spring将@Resource注解的name属性解析为bean的名字,而type属性则解析为bean的类型。

20.@ResponseBody详解

  • @ResponseBody的作用其实是将java对象转为json格式的数据。(作用在方法上)
  • @responseBody注解的作用是将controller的方法返回的对象通过适当的转换器转换为指定的格式之后,写入到response对象的body区,通常用来返回JSON数据或者是XML数据。
    注意:在使用此注解之后不会再走视图处理器,而是直接将数据写入到输入流中,他的效果等同于通过response对象输出指定格式的数据。
  • 在使用 @RequestMapping后,返回值通常解析为跳转路径,但是加上 @ResponseBody 后返回结果不会被解析为跳转路径,而是直接写入 HTTP response body 中。

21.事务

Spring框架中的事务:

  1. 事务管理器(接口):DataSourceTransactionManager

  2. 声明事务:直接或在xml文件中声明事务内容

    控制事务:隔离级别、传播行为、超时时间

  3. 处理方式:

    1. Spring中的@Transactional注解
    2. AspectJ框架可在xml配置文件中声明事务控制的内容

SpringBoot中使用事务:上面两种方式都可使用

  1. 在业务方法上加@Transactional注解,方法就有事务功能了

    @Service
    public class StudentServiceImpl implements StudentService {
        @Resource
        private StudentMapper studentMapper;
        @Transactional//启用事务,默认是可重复读、传播、超时 -1
        @Override
        public int addStu(Student student) {
            System.out.println("addStu..");
            int rows = studentMapper.insert(student);
            System.out.println("sql...");
    //        int m =10 / 0;异常会回滚事务
            return rows;
        }
    
  2. 明确在主启动类上加入@EnableTransactionManager

    @SpringBootApplication
    @MapperScan(basePackages = "com.jv.dao")
    @EnableTransactionManagement//启用事务管理器
    public class Application {
    
       public static void main(String[] args) {
          SpringApplication.run(Application.class, args);
       }
    
    }
    

22.MyBatis逆向工程

快速生成pojo及对应mapper.xml文件、dao类

  1. 添加插件:

    <plugins>
       <!--mybatis代码自动生成插件-->
       <plugin>
          <groupId>org.mybatis.generator</groupId>
          <artifactId>mybatis-generator-maven-plugin</artifactId>
          <version>1.3.6</version>
          <configuration>
             <!--配置文件的位置,src平级-->
             <configurationFile>GeneratorMapper.xml</configurationFile>
             <verbose>true</verbose>
             <overwrite>true</overwrite>
          </configuration>
       </plugin>
    
  2. 将GeneratorMapper.xml直接复制到项目的根目录下(src同级)

  3. 修改GeneratorMapper.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE generatorConfiguration
            PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
            "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
    
    <generatorConfiguration>
    
        <!-- 指定连接数据库的JDBC驱动包所在位置,指定到你本机的完整路径 -->
        <classPathEntry location="G:\program\Maven\apache-maven-3.6.3-bin\apache-maven-3.6.3\maven-repo\mysql\mysql-connector-java\8.0.29\mysql-connector-java-8.0.29.jar"/>
    
        <!-- 配置table表信息内容体,targetRuntime指定采用MyBatis3的版本 -->
        <context id="tables" targetRuntime="MyBatis3">
    
            <!-- 抑制生成注释,由于生成的注释都是英文的,可以不让它生成 -->
            <commentGenerator>
                <property name="suppressAllComments" value="true" />
            </commentGenerator>
    
            <!-- 配置数据库连接信息 -->
            <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
                            connectionURL="jdbc:mysql://localhost:3306/springdb?useUnicode=true&amp;characterEncoding=utf8&amp;serverTimezone=GMT%2B8&amp;nullCatalogMeansCurrent=true"
                            userId="root"
                            password="hsp">
            </jdbcConnection>
    
            <!-- 生成model类,targetPackage指定model类的包名, targetProject指定生成的model放在eclipse的哪个工程下面-->
            <javaModelGenerator targetPackage="com.jv.pojo"
                                targetProject="G:\idea_java_projects\springboot-jv\006-springboot\src\main\java">
                <property name="enableSubPackages" value="false" />
                <property name="trimStrings" value="false" />
            </javaModelGenerator>
    
            <!-- 生成MyBatis的Mapper.xml文件,targetPackage指定mapper.xml文件的包名, targetProject指定生成的mapper.xml放在eclipse的哪个工程下面 -->
            <sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources">
                <property name="enableSubPackages" value="false" />
            </sqlMapGenerator>
    
            <!-- 生成MyBatis的Mapper接口类文件,targetPackage指定Mapper接口类的包名, targetProject指定生成的Mapper接口放在eclipse的哪个工程下面 -->
            <javaClientGenerator type="XMLMAPPER" targetPackage="com.jv.dao" targetProject="src/main/java">
                <property name="enableSubPackages" value="false" />
            </javaClientGenerator>
    
            <!-- 数据库表名及对应的Java模型类名 -->
            <table tableName="student" domainObjectName="Student"
                   enableCountByExample="false"
                   enableUpdateByExample="false"
                   enableDeleteByExample="false"
                   enableSelectByExample="false"
                   selectByExampleQueryId="false"/>
    
        </context>
    
    </generatorConfiguration>
    

dao方法不全,pojo类属性不对的解决方法:在url中添加&nullCatalogMeansCurrent=true。

    <!-- 配置数据库连接信息 -->
    <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
                    connectionURL="jdbc:mysql://localhost:3306/springdb?useUnicode=true&amp;characterEncoding=utf8&amp;serverTimezone=GMT%2B8&amp;nullCatalogMeansCurrent=true"
                    userId="root"
                    password="hsp">
    </jdbcConnection>

23.接口架构风格——RESTful

  • 接口:API 应用程序接口 ,预先定义的接口函数、http接口,无需理解内部工作机制便能直接访问该应用的功能。

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

  • 框架风格:api组织形式(样子)

    传统:http://localhost:9002/mytrans/addstu?name=Lis&age=22 通过get方式传参

  • RESTful:

    1. REST(表现层状态转移),是一种接口的架构风格和设计的理念,但不是标准。优点:更简洁、更有层次

      就是使用url表示资源,使用http动作操作资源

    2. 表现层状态转移:资源本身的状态可以发生变化,CRUD可切换

    3. REST的要素:用REST表示资源和对资源的操作;

      • 资源使用url表示,名词表示,以及访问资源的信息

      • 使用http的动作(请求方式)表示对资源的操作(CRUD)

        GET查询、POST创建、PUT更新(需要隐藏put用post,)、DELETE删除

    4. REST风格:url中使用"/"分隔资源的信息

      http://localhost:9002/mytrans/addstu/Lis/22 通过get方式传参

    5. 需要的分页、排序等参数,依然放在url的后面

      http://localhost:9002/mytrans/addstu/Lis/22?page=1&pageSize=20

24.REST注解

  • @PathVariable:从url中获取数据

  • @GetMapper:支持get请求方式,等同于@RequsestMapping(method=RequestMethod.GET)

  • @PostMapping:支持post请求方式,等同于@RequsestMapping(method=RequestMethod.POST)

  • @PutMapping:支持put请求方式,等同于@RequsestMapping(method=RequestMethod.PUT)

  • @DeleteMapping:支持delete请求方式,等同于@RequsestMapping(method=RequestMethod.DELETE)

  • @RestController:复合注解,是@Controller和@ResponseBody的组合,

    ​ 使用后表示当前类的所有方法都加入了@ResponseBody

        @RestController
        public class MyRestController {
            @GetMapping("/student/{stuId}")
            public String queryStu(@PathVariable(value = "stuId") Integer id){
                return "query .."+id;
            }
        }
    	@PostMapping("/student/{name}/{age}")
        //当路径变量名和形参名一样,@PathVariable中的value可以不用写
        public String createStu(@PathVariable String name ,
                                @PathVariable Integer age){
            return "create ..name="+name + "#age="+age;
        }
        @PutMapping("/student/{id}/{age}")
        public String editStu(@PathVariable String id ,
                                @PathVariable Integer age){
            return "edit ..id="+id + "#age="+age;
        }
        @DeleteMapping("/student/{id}")
        public String delStu(@PathVariable String id){
            return "del ..id="+id ;
        }
    
  • 可用postman或idea自带的工具来测试post、put等请求方式;tools–>HTTP Client–>REST Client进入或alt+shift+ctrl+insert快捷键HTTP Request进入测试工具。

25.在页面中或ajax中,支持put、delete请求

  • 在SpringMvc中有一个过滤器支持post请求转为put、delete

  • 过滤器是org.springframework.web.filter.HiddenHttpMethodFilter,作用是将post请求转为put、delete

  • 实现:

    1. application.properties(yml):开启使用HiddenHttpMethodFilter过滤器

    2. 请求页面中,要包含_method参数,值是put、delete,但发起这个请求是post方式

      <input type="hidden" name="_method" value="put">
      

26.SpringBoot集成的Redis

  • Redis是一个NoSql数据库,常作用缓存Cache使用。

  • Redis的数据类型:string、hash、set、zset、list

  • Redis是一个中间件:是一个独立的服务器

  • Java中著名的客服端:Jedis、lettuce、Redisson

  • Springboot中有一个RedisTemplate处理和redis交互

  • 使用:

    • 增加NoSql起步依赖

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

27.StringRedisTemplate对比RedisTemplate

  • StringRedisTemplate:把k、v都作为string处理,使用的是String的序列化,可读性好
  • RedisTemplate:把k、v进过序列化后存到redis;k,v是序列化的内容不能直接识别
  • 序列化:将对象转化为可传输的字节序列过程称为序列化,目的是让对象可跨平台存储和进行网络传输
  • 常见序列化方式:JDK(不跨语言)、JSON、XML、Hessian、Kryo(不跨语言)、Thrift

28.Maven打包

  • war包:

    1. 创建了一个jsp应用

    2. 修改pom.xml

      1)指定打包后的文件名称

      <build>
         <!--打包后的文件名称-->
         <finalName>myboot</finalName>
      </build>
      

      2)指定jsp编译目录

      <!--resources插件, 把jsp编译到指定的目录-->
      <resources>
         <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>
      

      3)执行打包是war

      <!--打包类型-->
      <packaging>war</packaging>
      

      4)主启动类继承SpringBootServletInitializer

      /**
       * SpringBootServletInitializer: 继承这个类, 才能使用独立tomcat服务器
       */
      @SpringBootApplication
      public class JspApplication  extends SpringBootServletInitializer  {
      
         public static void main(String[] args) {
            SpringApplication.run(JspApplication.class, args);
         }
      
         @Override
         protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
            return builder.sources(JspApplication.class);
         }
      }
      

      5)部署war

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

  • jar包:

    1.创建了一个包含了jsp的项目

    2.修改pom.xml

    ​ 1) 指定打包后的文件名称

    <build>
       <!--打包后的文件名称-->
       <finalName>myboot</finalName>
    </build>
    

    2)指定springboot-maven-plugin版本

    <plugins>
       <plugin>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-maven-plugin</artifactId>
          <!--打包jar, 有jsp文件时,必须指定maven-plugin插件的版本是 1.4.2.RELEASE-->
          <version>1.4.2.RELEASE</version>
       </plugin>
    </plugins>
    

    3)最后执行 maven clean package

    ​ 在target目录中,生成jar 文件, 例子是myboot.jar

    ​ 执行独立的springboot项目 在cmd中执行: java -jar myboot.jar

29.Thymeleaf模板引擎

Thymeleaf: 是使用java开发的模板技术, 在服务器端运行。 把处理后的数据发送给浏览器。 模板是作视图层工作的。 显示数据的。 Thymeleaf是基于Html语言。 Thymleaf语法是应用在html标签中 。 SpringBoot框架集成Thymealeaf, 使用Thymeleaf代替jsp。

  1. 表达式

    1. 标准变量表达式(常用)

      语法:${key}

      作用:获取key对应的文本数据 ,key 是request作用域中的key , 使用request.setAttribute()或model.addAttribute(),在页面中的 html标签中,使用 th:text=“${key}” 来获取value

      <div>
          <!--/*@thymesVar id="stu" type="com.jv.pojo.Student"*/-->
          <p th:text="${stu.id}">表达式</p>
          <p th:text="${stu.name}">表达式</p>
          <p th:text="${stu.age}">表达式</p>
      </div>
      
    2. 选择变量表达式(星号变量表达式)

      语法:*{key}

      作用:获取这个key对应的数据,*{key}需要和th:object这个属性一起使用;目的是简化获取对象的属性值。

      <div th:object="${stu}">
          <p>使用*{}</p>
          <p th:text="*{id}"></p>
          <p th:text="*{name}"></p>
          <p th:text="*{age}"></p>
      </div>
      
    3. 连接表达式

      语法:@{url}

      作用:表示链接, 可以

       <script src="..."> , <link href="..."> <a href=".."> ,<form action="..."> <img src="...">
      

      使用例子:

      <body>
          <a th:href="@{http://www.baidu.com}">链接到百度</a>
      <!--    相对路径-->
          <a th:href="@{/tpl/query}">相对路径</a>
          <a th:href="@{'/tpl/query?id=1002'}">相对路径</a><br>
      <!--    推荐使用该传参方式-->
          <a th:href="@{/tpl/query(id=${stu.id})}">推荐,多个参数用逗号分隔</a>
      </body>
      
  2. 属性

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

    例如:

    <form action="/loginServlet" method="post"></form>
    
    <form th:action="/loginServlet" th:method="${methodAttr}"></form>
    
  3. each循环

    可以循环LIst、Array、Map

    语法:在一个html标签中,使用th:each

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

    “循环的状态变量”中的方法:index(从0开始循环到的下标)、count(从1开始的计数)、size(循环总的个数)等等

    each循环Map

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

    <div th:each="集合循环成员,循环的状态变量:${key}">
        <p th:text="${集合循环成员.key}" ></p>
        <p th:text="${集合循环成员.value}" ></p>
    </div>
    
    集合循环成员,循环的状态变量:两个名称都是自定义的。 “循环的状态变量”这个名称可以不定义,默认是"集合循环成员Stat"
    
    key:map集合中的key
    value:map集合key对应的value值
    
    
  4. if条件判断

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

    语法:
    <div th:if=" 10 > 0 "> 显示文本内容 </div>
    
    

    还有一个 th:unless 和 th:if相反的行为

    语法:
    <div th:unless=" 10 < 0 "> 当条件为false显示标签体内容 </div>
    

    例子:if

    <div style="margin-left: 400px">
            <h3> if 使用</h3>
            <p th:if="${sex=='m'}">性别是男</p>
            <p th:if="${isLogin}">已经登录系统</p>
            <p th:if="${age > 20}">年龄大于20</p>
            <!--""空字符是true-->
            <p th:if="${name}">name是“”</p>
            <!--null是false-->
            <p th:if="${isOld}"> isOld是null</p>
     </div>
    
    

    例子: unless

     <div style="margin-left: 400px">
            <h3>unless: 判断条件为false,显示标签体内容</h3>
            <p th:unless="${sex=='f'}">性别是男的</p>
            <p th:unless="${isLogin}">登录系统</p>
            <p th:unless="${isOld}"> isOld是null </p>
     </div>
    
  5. th:switch

    th:switch 和 java中的swith一样的,(都没有匹配到走th:case=“*”)

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

    1. 内联文本:在html标签外,获取表达式的值

      语法:(在标签外面使用)

      <p>显示姓名是:[[${key}]]</p>
      
       <div style="margin-left: 400px">
              <h3>内联 text, 使用内联表达式显示变量的值</h3>
              <div th:inline="text">
                  <p>我是[[${name}]],年龄是[[${age}]]</p>
                  我是<span th:text="${name}"></span>,年龄是<span th:text="${age}"></span>
              </div>
      
              <div>
                  <p>使用内联text</p>
                  <p>我是[[${name}]],性别是[[${sex}]]</p>
              </div>
      </div>
      
    2. 内联javascript

      例子:
       <script type="text/javascript" th:inline="javascript">
               var myname = [[${name}]];
               var myage = [[${age}]];
      
               //alert("获取的模板中数据 "+ myname + ","+myage)
      
              function fun(){
                  alert("单击事件,获取数据 "+ myname + ","+ [[${sex}]])
              }
          </script>
      
  7. 字面量

    例子:

     <div style="margin-left: 400px">
           <h3>文本字面量: 使用单引号括起来的字符串</h3>
           <p th:text="'我是'+${name}+',我所在的城市'+${city}">数据显示</p>
    
           <h3>数字字面量</h3>
            <p th:if="${20>5}"> 20大于 5</p>
    
            <h3>boolean字面量</h3>
            <p th:if="${isLogin == true}">用户已经登录系统</p>
    
            <h3>null字面量</h3>
            <p th:if="${myuser != null}">有myuser数据</p>
        </div>
    
  8. 字符串连接

    连接字符串有两种语法

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

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

    2)语法:使用双竖线, |字符串和表达式|,更推荐

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

    例子:

        <div style="margin-left: 400px">
           <h3>字符串连接方式1:使用单引号括起来的字符串</h3>
           <p th:text="'我是'+${name}+',我所在的城市'+${city}">数据显示</p>
            <br/>
            <br/>
            <h3>字符串连接方式2:|字符串和表达式|</h3>
            <p th:text="|我是${name},所在城市${city},其他人${myuser.name}|"></p>
        </div>
    
  9. 运算符

    算术运算: + , - - , * , / , %
    关系比较: > , < , >= , <= ( gt , lt , ge , le )
    相等判断: == , != ( eq , ne )

    <div style="margin-left: 400px">
            <h3>使用运算符</h3>
            <p th:text="${age > 10}">年龄大于 10 </p>
            <p th:text="${ 20 + 30 }">显示运算结果</p>
            <p th:if="${myuser == null}">myuser是null</p>
            <p th:if="${myuser eq null}">myuser是null</p>
            <p th:if="${myuser ne null}">myuser不是null</p>
    
            <p th:text="${isLogin == true ? '用户已经登录' : '用户需要登录'}"></p>
            <p th:text="${isLogin == true ? ( age > 10 ? '用户是大于10的' : '用户年龄比较小') : '用户需要登录'}"></p>
    
        </div>
    
    三元运算符:
     表达式  ? true的结果 : false的结果
    
    三元运算符可以嵌套
    
    
  10. 内置对象

    文档地址:https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#web-context-namespaces-for-requestsession-attributes-etc.

    #request 表示 HttpServletRequest

    #session 表示 HttpSession对象

    session 表示Map对象的, 是#session的简单表示方式, 用来获取session中指定的key的值

    ​ #session.getAttribute(“loginname”) == session.loginname

    这些是内置对象,可以在模板文件中直接使用。

    例子:
     <div style="margin-left: 350px">
            <h3>内置对象#request,#session,session的使用</h3>
            <p>获取作用域中的数据</p>
            <p th:text="${#request.getAttribute('requestData')}"></p>
            <p th:text="${#session.getAttribute('sessionData')}"></p>
            <p th:text="${session.loginname}"></p>
    
            <br/>
            <br/>
            <h3>使用内置对象的方法</h3>
            getRequestURL=<span th:text="${#request.getRequestURL()}"></span><br/>
            getRequestURI=<span th:text="${#request.getRequestURI()}"></span><br/>
            getQueryString=<span th:text="${#request.getQueryString()}"></span><br/>
            getContextPath=<span th:text="${#request.getContextPath()}"></span><br/>
            getServerName=<span th:text="${#request.getServerName()}"></span><br/>
            getServerPort=<span th:text="${#request.getServerPort()}"></span><br/>
    </div>
    
  11. 内置工具类

    内置工具类型: Thymeleaf自己的一些类,提供对string, date ,集合的一些处理方法

    #dates: 处理日器的工具类

    #numbers:处理数字的

    #lists: 处理list集合的

    <div style="margin-left: 350px">
          <h3>日期类对象 #dates</h3>
          <p th:text="${#dates.format(mydate )}"></p>
          <p th:text="${#dates.format(mydate,'yyyy-MM-dd')}"></p>
          <p th:text="${#dates.format(mydate,'yyyy-MM-dd HH:mm:ss')}"></p>
          <p th:text="${#dates.year(mydate)}"></p>
          <p th:text="${#dates.month(mydate)}"></p>
          <p th:text="${#dates.monthName(mydate)}"></p>
          <p th:text="${#dates.createNow()}"></p>
          <br/>
    
          <h3>内置工具类#numbers,操作数字的</h3>
          <p th:text="${#numbers.formatCurrency(mynum)}"></p>
          <p th:text="${#numbers.formatDecimal(mynum,5,2)}"></p>
    
          <br/>
          <h3>内置工具类#strings,操作字符串</h3>
          <p th:text="${#strings.toUpperCase(mystr)}"></p>
          <p th:text="${#strings.indexOf(mystr,'power')}"></p>
          <p th:text="${#strings.substring(mystr,2,5)}"></p>
          <p th:text="${#strings.substring(mystr,2)}"></p>
          <p th:text="${#strings.concat(mystr,'---java开发的黄埔军校---')}"></p>
          <p th:text="${#strings.length(mystr)}"></p>
          <p th:text="${#strings.length('hello')}"></p>
          <p th:unless="${#strings.isEmpty(mystr)}"> mystring 不是 空字符串  </p>
    
          <br/>
          <h3>内置工具类#lists,操作list集合</h3>
          <p th:text="${#lists.size(mylist)}"></p>
          <p th:if="${#lists.contains(mylist,'a')}">有成员a</p>
          <p th:if="!${#lists.isEmpty(mylist)}"> list 集合有多个成员</p>
    
          <br/>
          <h3>处理null</h3>
          <p th:text="${zoo?.dog?.name}"></p>
    
      </div>
    
  12. 自定义模板

    模板是内容复用, 定义一次,在其他的模板文件中多次使用。

    模板使用:

    1.定义模板

    2.使用模板

    模板定义语法:th:fragment=“模板自定义名称”

    例如:
    <div th:fragment="head">
        <p>
            jvjava开发
        </p>
        <p>
            www.jv.com
        </p>
    </div>
    

    引用模板语法:

    1) ~{templatename :: selector}
       templatename:  文件名称
       selector: 自定义模板名称
    2)templatename :: selector
       templatename:  文件名称
       selector: 自定义模板名称
    
    对于使用模板:有包含模板(th:include), 插入模板(覆盖)(th:insert)
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值