Spring Boot 学习笔记

打印 上一主题 下一主题

主题 563|帖子 563|积分 1689

SpringBoot 简介


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

使用 java 类作为 xml 配置文件的替代, 是配置 spring 容器的纯 java 的方式。
在这个 java 类中可以创建 java 对象,把对象放入 spring 容器中(注入到容器)。
对于此JavaConfig相关的示例创建的是普通的Java项目,并非SpringBoot项目!
@Configuration


  • 放在类的上面,表示此类作为配置文件使用,相当于一个配置类
@Bean


  • 放在配置类中的方法上面,用来声明对象,将对象注入到容器中
  • 方法返回值需要是注入的对象类型
  • 若没有配置@Bean中的 name 属性,则从容器中获取该对象需要用其方法名
  • 若配置了@Bean中的 name 属性,则从容器中获取该对象需要用配置的 name 名称
需要使用到两个注解:

  • @Configuration:放在一个类的上面,表示这个类是作为配置文件使用的。
  • @Bean:放在配置类中的方法上,声明对象,把对象注入到容器中。
配置类示例:
  1. /**
  2. * Configuration:表示当前类是作为配置文件使用的。 就是用来配置容器的
  3. *       位置:在类的上面
  4. *
  5. *  SpringConfig这个类就相当于beans.xml
  6. */
  7. @Configuration
  8. public class SpringConfig {
  9.     /**
  10.      * 创建方法,方法的返回值是对象。 在方法的上面加入@Bean
  11.      * 方法的返回值对象就注入到容器中。
  12.      *
  13.      * @Bean: 把对象注入到spring容器中。 作用相当于<bean>
  14.      *
  15.      *     位置:方法的上面
  16.      *
  17.      *     说明:@Bean,不指定对象的名称,默认是方法名是 id
  18.      *
  19.      */
  20.     @Bean
  21.     public Student createStudent(){
  22.         Student s1  = new Student();
  23.         s1.setName("张三");
  24.         s1.setAge(26);
  25.         s1.setSex("男");
  26.         return s1;
  27.     }
  28.     /***
  29.      * 指定对象在容器中的名称(指定<bean>的id属性)
  30.      * @Bean的name属性,指定对象的名称(id)
  31.      */
  32.     @Bean(name = "lisiStudent")
  33.     public Student makeStudent(){
  34.         Student s2  = new Student();
  35.         s2.setName("李四");
  36.         s2.setAge(22);
  37.         s2.setSex("男");
  38.         return s2;
  39.     }
  40. }
复制代码
测试:
  1. public class MyTest {
  2.     @Test
  3.     public void test01() {
  4.         // 使用配置文件方式声明的bean,需要用 ClassPathXmlApplicationContext,参数传配置文件路径
  5.         ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
  6.         Student student = (Student) context.getBean("myStudent");
  7.         System.out.println(student);
  8.     }
  9.     @Test
  10.     public void test02() {
  11.         // 使用配置类方式将对象注入到容器,需要使用 AnnotationConfigApplicationContext,参数传配置类的class
  12.         ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
  13.         // 配置类中方法的Bean设置name属性,则通过name属性名获取对象;否则默认可通过其方法名获取
  14.         Student s = (Student) ctx.getBean("lisiStudent");
  15.         // Student s = (Student) ctx.getBean("makeStudent");
  16.         // Student s = (Student) ctx.getBean("createStudent");
  17.         System.out.println(s);
  18.     }
  19. }
复制代码
小结:

  • 使用配置类的方式,需要在配置类上使用@Configuration;需要在配置类中的方法上使用@Bean声明对象,将对象注入到容器中。
  • 配置类中的方法返回值类型是需要注入的对象类型;若未配置@Bean中的 name 属性,则获取该对象时需要使用方法名获取;若配置了@Bean中的 name 属性,则通过配置的 name 名称获取该对象。
  • 创建容器对象时,不再使用ClassPathXmlApplicationContext接口实现类,不再通过配置文件来注入到容器对象中;而是使用AnnotationConfigApplicationContext接口实现类,通过配置类的 class 来将对象注入到容器。
@ImportResource


  • 使用在配置类的上面
  • 作用是导入其他的 xml 配置文件, 等于在 xml 中使用
  • 需要在 value 属性中指定配置文件的路径
  1. @Configuration
  2. @ImportResource(value = "classpath:applicationContext.xml")
  3. public class SpringConfig {
  4. }
复制代码
@PropertySource


  • 使用在配置类的上面
  • 用来读取 properties 属性配置文件
  • 使用属性配置文件可以实现外部化配置 ,在程序代码之外提供数据。
@ComponentScan:使用在配置类上,扫描指定包中注解,来创建对象以及给属性赋值
示例:
  1. --配置类--
  2. @Configuration
  3. @ImportResource(value = "classpath:applicationContext.xml")  // 导入xml配置文件
  4. @PropertySource(value = "classpath:config.properties")  // 读取属性配置文件
  5. @ComponentScan(basePackages = "com.luis.vo")  // 声明组件扫描器,扫描指定包中的注解
  6. public class SpringConfig {
  7. }
  8. --config.properties--
  9. tiger.name=东北虎
  10. tiger.age=3
  11. --vo数据类--   
  12. @Component("tiger")
  13. public class Tiger {
  14.     @Value("${tiger.name}")
  15.     private String name;
  16.     @Value("${tiger.age}")
  17.     private Integer age;   
  18. }  
  19. --测试--
  20. @Test
  21. public void test04() {
  22.     ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
  23.     Tiger tiger = (Tiger) ctx.getBean("tiger");
  24.     System.out.println(tiger);
  25. }   
复制代码
SpringBoot 入门

SpringBoot 是 Spring 中的一个成员,可简化 Spring,SpringMVC 的使用。
其核心还是 IOC 容器。
SpringBoot 特点


  • Create stand-alone Spring applications
    创建 spring 应用
  • Embed Tomcat, Jetty or Undertow directly (no need to deploy WAR files)
    有内嵌的 tomcat,jetty,Undertow
  • Provide opinionated 'starter' dependencies to simplify your build configuration
    提供了 starter 起步依赖,简化应用的配置。
    比如使用 MyBatis 框架,需要在 Spring 项目中,配置 MyBatis 的对象 SqlSessionFactory ,Dao 的代理对象
    如今在 SpringBoot 项目中,在 pom.xml 里面,只需加入一个 mybatis-spring-boot-starter 依赖即可
  • Automatically configure Spring and 3rd party libraries whenever possible
    尽可能去配置 spring 和第三方库,也叫做自动配置(就是把 spring 中的,第三方库中的对象都创建好,放到容器中,开发人员可以直接使用)
  • Provide production-ready features such as metrics, health checks, and externalized configuration
    提供了健康检查,统计,外部化配置
  • Absolutely no code generation and no requirement for XML configuration
    不用生成代码,不用使用xml,做配置
创建 SpringBoot 项目的三种方式

创建 SpringBoot 项目有三种方式:

  • 使用 Spring 提供的初始化器,就是使用向导创建 SpringBoot 应用(使用 https://start.spring.io 地址)【联网】
  • 使用 Spring 提供的初始化器,就是使用向导创建 SpringBoot 应用(使用国内的 https://start.springboot.io 地址)【联网】
    还可以选择使用阿里云的地址进行创建:https://start.aliyun.com
  • 先直接创建 maven 项目,然后补充相关依赖,补全目录结构即可【不需联网】
创建简单 SpringBoot web 项目示例:(以下选择向导方式创建)

  • 新建 SpringBoot 模块,选择 Spring Initializr向导创建
  • 配置项目相关信息,依赖选择 Spring Web 进行创建
  • 整理项目结构以及 pom 文件
  • 在主启动类所在的包下创建 controller 控制器类
    1. @Controller
    2. public class HelloSpringBoot {
    3.     @RequestMapping("/hello")
    4.     @ResponseBody
    5.     public String helloSpringBoot() {
    6.         return "欢迎使用SpringBoot";
    7.     }
    8. }
    复制代码
  • 查看是否配置有 Spring Boot 启动服务,若没有则进行配置
  • 运行主启动类的 main 方法或 IDEA 主面板运行项目
  • 浏览器输入地址访问 http://localhost:8080/hello(默认8080端口,无上下文)
@SpringBootApplication


  • 其自动配置在主类之上,每个 SpringBoot 项目都会有一个主类
    1. @SpringBootApplication
    2. public class SpringbootTest03Application {
    3.     public static void main(String[] args) {
    4.         SpringApplication.run(SpringbootTest03Application.class, args);
    5.     }
    6. }
    复制代码
  1. @SpringBootApplication
  2. 是一个复合注解,包含以下三个注解(以下注解的功能其全具备)
  3. @SpringBootConfiguration  -----> 该注解标注的类可当做配置类使用
  4. @EnableAutoConfiguration  -----> 启用自动配置,将常用框架以及第三方对象创建好
  5. @ComponentScan  -----> 可扫描到该注解标注的类的包及其子包下其他注解
  6.    
  7. 详解:   
  8. 1.@SpringBootConfiguration
  9.    
  10. @Configuration
  11. public @interface SpringBootConfiguration {
  12.     @AliasFor(
  13.         annotation = Configuration.class
  14.     )
  15.     boolean proxyBeanMethods() default true;
  16. }
  17. 说明:使用了@SpringBootConfiguration注解标注的类,可以作为配置文件使用,
  18.     可以使用@Bean声明对象,注入到容器,
  19.     故主类可作为一个配置类使用,在其类中可在方法上使用@Bean声明对象
  20. 2.@EnableAutoConfiguration
  21. 启用自动配置,把java对象配置好,注入到spring容器中;例如可以把mybatis的对象创建好,放入到容器中。
  22.    
  23. 3.@ComponentScan
  24. 扫描器,找到注解,根据注解的功能创建对象,给属性赋值等。
  25. 默认扫描的包: @ComponentScan所标注的类所在的包和子包。   
复制代码
SpringBoot 的配置文件

避免中文乱码,需要在 IDEA 中设置 encoding 为 UTF-8
配置文件名: application
扩展名有:properties( k=v) 以及 yml ( k: v)
可使用 application.properties,application.yml 两种文件格式
创建 SpringBoot 项目时默认创建的是 application.properties 配置文件格式
以下为配置示例:
例1:application.properties 中设置端口和上下文
  1. # 设置端口
  2. server.port=8888
  3. # 设置访问应用的上下文路径
  4. server.servlet.context-path=/myWeb
复制代码
例2:application.yml 中设置端口和上下文(推荐使用)
这种格式的配置文件,结构比较清晰
注意:value 值前有一个空格
  1. server:
  2.   port: 8083
  3.   servlet:
  4.     context-path: /myboot
复制代码
注意:如果同时存在两种格式的配置文件,即 application.properties 和 application.yml 两个配置文件同时存在,则默认使用 application.properties 这种格式中的配置!
多环境配置的应用

有开发环境,测试环境,上线的环境。
每种环境有不同的配置信息,例如端口,上下文访问路径,数据库 url,用户名,密码等,所以需要多种环境配置。
使用多环境配置文件,可以方便的切换不同的配置。
多环境配置方式:

  • 创建多个配置文件,文件命名规则:application-环境名称.properties(yml)【一般环境名使用 dev/test/online 这几种】
    创建开发环境的配置文件:application-dev.yml
    1. #项目开发使用的环境
    2. server:
    3.   port: 8080
    4.   servlet:
    5.     context-path: /mydev
    复制代码
    创建测试环境的配置文件:application-test.yml
    1. #项目测试使用的环境
    2. server:
    3.   port: 8081
    4.   servlet:
    5.     context-path: /mytest
    复制代码
    创建上线环境的配置文件:application-online.yml
    1. #项目上线使用的环境
    2. server:
    3.   port: 8082
    4.   servlet:
    5.     context-path: /myonline
    复制代码
  • 在主配置文件 application.yml 中激活要使用的环境【激活的配置信息是根据多环境文件的命名来确定】
    主配置文件中激活要使用的环境:application.yml
    1. #激活使用的环境
    2. spring:
    3.   profiles:
    4.     active: online
    复制代码
使用 @Value 读取配置文件数据

我们可以在主配置文件中使用 key-value 键值对的格式进行数据的配置;
因为主配置文件已经由 Spring 自动管理,所以可以直接在自己写的控制器类的属性上通过 @Value("${server.port}")读取配置文件中数据,并对属性进行赋值。
  1. @Controller
  2. public class MyController {
  3.     @Value("${server.port}")
  4.     private Integer port;
  5.     @Value("${server.servlet.context-path}")
  6.     private String contextPath;
  7.     @Value("${project.name}")
  8.     private String projectName;
  9.     @Value("${project.dev}")
  10.     private String projectDev;
  11.     @RequestMapping("/data")
  12.     @ResponseBody
  13.     public String queryData() {
  14.         return port + "========> port " + contextPath + "========> contextPath "
  15.                 + projectName + "========> projectName " + projectDev + "========> projectDev";
  16.     }
  17. }
复制代码
@ConfigurationProperties


  • 使用位置:类的上面
  • 作用:把配置文件中符合条件的数据映射为 java 对象
  • 需要配置其 prefix 属性:即配置文件中的某些 key 开头的内容
使用示例:@ConfigurationProperties(prefix = "school")
使用解释:类上添加@ConfigurationProperties注解后,其将从属性配置文件中找以配置的 prefix 属性值,即school开头的配置,将所有 school后面的配置参数与该类中的所有属性相比较,如果匹配成功,则将配置文件中配置的对应的数据赋值给该类中同名属性,完成数据映射。
使用示例:

  • 在配置文件 application.properties 中配置自定义数据
    1. #配置端口号
    2. server.port=8888
    3. #配置上下文访问路径
    4. server.servlet.context-path=/myboot
    5. #自定义数据
    6. school.name=哈师大
    7. school.addr=东北
    8. school.level=2
    复制代码
  • 创建数据对象
    1. @Component
    2. @ConfigurationProperties(prefix = "school")
    3. public class SchoolInfo {
    4.     private String name;
    5.     private String addr;
    6.     private Integer level;
    7.     // getter,setter,toString...
    8. }   
    复制代码
  • 创建控制器类
    1. @Controller
    2. public class MyController {
    3.     @Resource
    4.     private SchoolInfo info;
    5.     @RequestMapping("/info")
    6.     @ResponseBody
    7.     public String querySchoolInfo() {
    8.         return "info = " + info;
    9.     }
    10. }
    复制代码
  • 运行,访问测试
    1. 访问:http://localhost:8888/myboot/info
    2. 结果:info = SchoolInfo{name='哈师大', addr='东北', level=2}
    复制代码
SpringBoot 中使用 JSP(不推荐,了解即可)

SpringBoot 默认不支持 JSP,需要进行相关配置才能使用 JSP。
JSP 技术慢慢被淘汰,有更好的技术替代它。
使用 SpringBoot 框架时不推荐使用 JSP,后面将使用 Thymeleaf 模板技术完全替代 JSP!
使用步骤:

  • 创建 SpringBoot 项目,整理项目结构和 pom 文件
  • 添加一个处理 JSP 的依赖,负责编译 JSP 文件(如果需要使用 servlet jsp jstl 功能则需要另外加对应依赖)
    1. <dependency>
    2.     <groupId>org.apache.tomcat.embed</groupId>
    3.     <artifactId>tomcat-embed-jasper</artifactId>
    4. </dependency>
    5. <dependency>
    6.         <groupId>javax.servlet</groupId>
    7.         <artifactId>jstl</artifactId>
    8. </dependency>
    9. <dependency>
    10.         <groupId>javax.servlet</groupId>
    11.         <artifactId>javax.servlet-api</artifactId>
    12. </dependency>
    13. <dependency>
    14. <groupId>javax.servlet.jsp</groupId>
    15.         <artifactId>javax.servlet.jsp-api</artifactId>
    16.         <version>2.3.1</version>
    17. </dependency>
    复制代码
  • 在 main 目录下创建一个名为 webapp 的目录(名称固定);在项目工程结构中设置该目录为 web 资源目录(进入项目结构设置后,点击 Web 选项,从 Web Resource Directories 下添加新创建的 webapp 目录为 web 资源目录即可)
  • 在 webapp 目录下新建 index.jsp 用来显示 controller 中的数据
    1. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    2. <html>
    3. <head>
    4.     <title>jsp</title>
    5. </head>
    6. <body>
    7.     SpringBoot中使用JSP显示数据:${data}
    8. </body>
    9. </html>
    复制代码
  • 创建 controller 控制器类,指定数据和视图
    1. @Controller
    2. public class JspController {
    3.     @RequestMapping("/myjsp")
    4.     public String doJsp(Model model) {
    5.         // 将数据放到request中(与request.setAttribute作用相同)
    6.         model.addAttribute("data", "SpringBoot使用JSP");
    7.         return "index";
    8.     }
    9. }
    复制代码
  • 配置文件中配置视图解析器,端口号以及上下文等信息
    1. #配置端口号
    2. server.port=7070
    3. #配置上下文访问路径
    4. server.servlet.context-path=/myboot
    5. #配置视图解析器
    6. # / = src/main/webapp
    7. spring.mvc.view.prefix=/
    8. spring.mvc.view.suffix=.jsp
    复制代码
  • 在 pom.xml 中指定 jsp 文件编译后的存放目录【在 pom 的 build 标签下进行指定】
    修改 pom 文件后,记得重新加载下,确保 pom 文件资源完全刷新!
    1. <resources>
    2.     <resource>
    3.         
    4.         <directory>src/main/webapp</directory>
    5.         
    6.         <targetPath>META-INF/resources</targetPath>
    7.         
    8.         <includes>
    9.             <include>**/*.*</include>
    10.         </includes>
    11.     </resource>
    12. </resources>
    复制代码
  • 直接运行并启动主程序,输入地址访问测试
    1. http://localhost:7070/myboot/myjsp
    复制代码
两点需要注意下:

  • 必须添加处理 jsp 的依赖
  • 必须指定 jsp 编译后的存放目录
原因:因为 SpringBoot 使用的是内嵌的 Tomcat
SpringBoot 使用容器 ApplicationContext

使用场景:不想启动整个项目,只想测试某个功能,就可直接通过run方法获取容器对象,通过容器对象进行相关测试。
如果想通过代码,从容器中获取对象:
通过SpringApplication.run(Application.class, args); 其返回值即可获取容器对象。
SpringApplication.run(SpringbootUseJspApplication.class, args)返回的就是一个 ApplicationContext 容器对象!
  1. 解析:SpringApplication.run(SpringbootUseJspApplication.class, args);
  2. 点进其run方法:
  3. public static ConfigurableApplicationContext run(Class<?> primarySource, String... args) {
  4.     return run(new Class[]{primarySource}, args);
  5. }   
  6. 查看ConfigurableApplicationContext类:
  7. public interface ConfigurableApplicationContext extends ApplicationContext, Lifecycle, Closeable {...}   
  8. 总结:通过run方法获取的是容器对象ApplicationContext的子类,即也是一个容器对象。
复制代码
容器使用示例:

  • 创建 SpringBoot 项目时选择 Spring Web 依赖,整理项目目录和 pom 文件
  • 创建 service 接口及其实现类,定义测试方法
    1. public interface UserService {
    2.     void sayHello(String name);
    3. }
    4. @Service("userService")
    5. public class UserServiceImpl implements UserService {
    6.     @Override
    7.     public void sayHello(String name) {
    8.         System.out.println("hello " + name);
    9.     }
    10. }
    复制代码
  • 在主启动类中直接获取并使用容器对象进行测试
    1. @SpringBootApplication
    2. public class SpringbootUseContainerApplication {
    3.     public static void main(String[] args) {
    4.         // 直接通过run方法获取容器对象
    5.         ApplicationContext ctx = SpringApplication.run(SpringbootUseContainerApplication.class, args);
    6.         // 从容器中获取指定对象
    7.         UserService userService = (UserService) ctx.getBean("userService");
    8.         // 调用对象的方法进行测试
    9.         userService.sayHello("luis");
    10.     }
    11. }
    复制代码
CommandLineRunner 和 ApplcationRunner 接口

介绍:这两个接口都有一个 run 方法。
执行时机:容器对象创建好后自动会执行接口中的 run() 方法
使用场景:需要在容器启动后执行一些内容,比如读取配置文件,数据库连接之类的。
使用方式:实现接口,重写 run 方法,方法中写需要在容器启动后待执行的内容。
  1. @FunctionalInterface
  2. public interface CommandLineRunner {
  3.     void run(String... args) throws Exception;
  4. }
  5. @FunctionalInterface
  6. public interface ApplicationRunner {
  7.     void run(ApplicationArguments args) throws Exception;
  8. }
复制代码
使用示例:(以下以实现 CommandLineRunner接口为例)

  • 创建 SpringBoot 项目,不用选择依赖,整理项目目录和 pom 文件
  • 新建 service 接口以及实现类,定义测试方法
    1. public interface UserService {
    2.     void sayHello(String name);
    3. }
    4. @Service("userService")
    5. public class UserServiceImpl implements UserService {
    6.     @Override
    7.     public void sayHello(String name) {
    8.         System.out.println("你好," + name);
    9.     }
    10. }
    复制代码
  • 让启动类实现 CommandLineRunner接口,重写 run 方法进行测试
    1. @SpringBootApplication
    2. public class SpringbootRunApplication implements CommandLineRunner {
    3.     @Resource
    4.     private UserService userService;
    5.     public static void main(String[] args) {
    6.         System.out.println("main start");
    7.         // 创建容器对象
    8.         SpringApplication.run(SpringbootRunApplication.class, args);
    9.         System.out.println("main end");
    10.     }
    11.     @Override
    12.     public void run(String... args) throws Exception {
    13.         System.out.println("容器对象创建后执行此run方法");
    14.         // 此方法在容器对象创建后自动执行
    15.         // 可在此调用容器对象中的方法
    16.         userService.sayHello("jack");
    17.     }
    18. }
    复制代码
  • 运行主程序,进行测试
    运行结果:
    1. main start
    2. 容器对象创建后执行此run方法
    3. 你好,jack
    4. main end
    复制代码
SpringBoot 和 Web 组件

讲三个内容:拦截器、Servlet、Filter
SpringBoot 中使用拦截器

拦截器是 SpringMVC 中的一种对象,能拦截对 Controller 的请求。
在框架中有系统实现好的拦截器, 也可以自定义拦截器,实现对请求的预先处理。
回顾 SpringMVC 中使用拦截器


  • 创建类实现 SpringMVC 框架的 HandlerInterceptor 接口,重写对应的方法
    1. public interface HandlerInterceptor {
    2. default boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    3.      return true;
    4. }
    5. default void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
    6. }
    7. default void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
    8. }
    9. }
    复制代码
  • 在 SpringMVC 的配置文件中,声明拦截器
    1. <mvc:interceptors>
    2.         <mvc:interceptor>
    3.             <mvc:path="url" />
    4.         <bean />
    5.     </mvc:interceptor>
    6. </mvc:interceptors>
    复制代码
SpringBoot 中使用拦截器

示例:

  • 创建 SpringBoot 项目,选择 Spring Web 依赖,整理项目目录和 pom 文件
  • 创建拦截器类,实现 HandlerInterceptor接口,重写相关方法
    1. public class LoginInterceptor implements HandlerInterceptor {
    2.     @Override
    3.     public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    4.         System.out.println("执行LoginInterceptor拦截器类的preHandle方法");
    5.         return true;
    6.     }
    7. }
    复制代码
  • 创建自定义配置类实现 WebMvcConfigurer接口,重写addInterceptors接口方法,在此方法中进行拦截器的相关配置(注入拦截器对象,指定拦截地址等)
    1. @Configuration // 成为配置类=====
    2. public class MyAppConfig implements WebMvcConfigurer {
    3.     // 重写addInterceptors方法,添加拦截器对象,注入到容器中
    4.     @Override
    5.     public void addInterceptors(InterceptorRegistry registry) {
    6.         // 创建拦截器对象
    7.         HandlerInterceptor loginInterceptor = new LoginInterceptor();
    8.         // 指定拦截的请求URI地址
    9.         String[] path = {"/user/**"};
    10.         // 指定不拦截的URI地址
    11.         String[] excludePath = {"/user/login"};
    12.         // 添加拦截器对象,指定拦截以及不拦截的URI地址
    13.         registry.addInterceptor(loginInterceptor)
    14.                 .addPathPatterns(path)
    15.                 .excludePathPatterns(excludePath);
    16.     }
    17. }
    复制代码
  • 创建控制器类,进行资源访问拦截测试
    1. @Controller
    2. @RequestMapping("/user")
    3. public class BootController {
    4.     @RequestMapping("/account")
    5.     @ResponseBody
    6.     public String userAccount() {
    7.         return "访问/user/account地址";
    8.     }
    9.     @RequestMapping("/login")
    10.     @ResponseBody
    11.     public String userLogin() {
    12.         return "访问/user/login地址";
    13.     }
    14. }
    复制代码
  • 运行主程序,进行访问测试
    1. 分别访问下列两个地址:
    2. http://localhost:8080/user/account
    3. http://localhost:8080/user/login
    4. 访问的测试结果:
    5. 访问http://localhost:8080/user/account时,后台有拦截器拦截信息输出【此请求走拦截器,被拦截器拦截】
    6. 访问http://localhost:8080/user/login时,后台无拦截器拦截信息输出【此请求不走拦截器,不会被拦截器拦截】
    复制代码
SpringBoot 中使用 Servlet

使用步骤:

  • 创建 SpringBoot 项目,选择 Spring Web 依赖,整理项目目录和 pom 文件
  • 创建 servlet 类,继承 HttpServlet,重写相关方法
    1. public class MyServlet extends HttpServlet {
    2.     // 直接重写service方法,则doGet和doPost请求都直接走此方法
    3.     @Override
    4.     protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    5.         // 设置字符编码
    6.         response.setContentType("text/html;charset=UTF-8");
    7.         // 使用应答对象HttpServletResponse,输出应答结果
    8.         PrintWriter out = response.getWriter();
    9.         out.print("SpringBoot中使用Servlet");
    10.         out.flush();
    11.         out.close();
    12.     }
    13. }
    复制代码
  • 创建自定义配置类,在类中定义指定返回值类型的方法,注册 Servlet 对象
    1. @Configuration
    2. public class WebApplicationConfig {
    3.     // ====定义指定返回值类型的方法,注册servlet对象====
    4.     @Bean
    5.     public ServletRegistrationBean servletRegistrationBean() {
    6.         // 两种方式注册servlet:
    7.         // 方式一:使用ServletRegistrationBean对象的有参构造
    8.         // 下列对象构造方法参数:第一个是需要注册的servlet对象,第二个是对应servlet的访问地址
    9.         // ServletRegistrationBean bean = new ServletRegistrationBean(new MyServlet(), "/login1", "/login2");
    10.         // 方式二:使用ServletRegistrationBean对象的无参构造
    11.         ServletRegistrationBean bean = new ServletRegistrationBean();
    12.         bean.setServlet(new MyServlet());
    13.         bean.addUrlMappings("/login3", "/login4");
    14.         return bean;
    15.     }
    16. }
    复制代码
  • 运行主程序,输入地址访问测试
    1. http://localhost:8080/login1
    2. http://localhost:8080/login2
    3. http://localhost:8080/login3
    4. http://localhost:8080/login4
    复制代码
SpringBoot 中使用过滤器

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

  • 创建 SpringBoot 项目,选择 Spring Web 依赖,整理项目目录和 pom 文件,刷新 pom
  • 创建自定义的过滤器类,实现 javax.servlet.Filter 接口,重写 doFilter 方法(注意实现的是 servlet 中的 Filter 接口)
    1. public class MyFilter implements Filter {
    2.    
    3.     @Override
    4.     public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    5.         System.out.println("执行自定义过滤器类MyFilter中的doFilter方法");
    6.         // 放行
    7.         filterChain.doFilter(servletRequest, servletResponse);
    8.     }
    9. }
    复制代码
  • 创建自定义配置类,在类中定义指定返回值类型的方法,注册过滤器对象
    1. @Configuration
    2. public class WebApplicationConfig {
    3.     @Bean
    4.     public FilterRegistrationBean filterRegistrationBean() {
    5.         
    6.         // 注册自定义过滤器类,并指定过滤的地址
    7.         FilterRegistrationBean bean = new FilterRegistrationBean();
    8.         bean.setFilter(new MyFilter());
    9.         bean.addUrlPatterns("/user/*");
    10.         return bean;
    11.     }
    12. }
    复制代码
  • 创建控制器类,进行资源访问过滤测试
    1. @Controller
    2. public class CustomFilterController {
    3.     @RequestMapping("/user/login")
    4.     @ResponseBody
    5.     public String userLogin() {
    6.         return "访问/user/login";
    7.     }
    8.     @RequestMapping("/query")
    9.     @ResponseBody
    10.     public String query() {
    11.         return "访问/query";
    12.     }
    13. }
    复制代码
  • 运行主启动类,输入访问地址测试
    1. http://localhost:8080/query
    2. http://localhost:8080/user/login
    复制代码
SpringBoot 中使用字符集过滤器

一般,都是使用字符集过滤器 CharacterEncodingFilter解决 post 请求中文乱码的问题。
CharacterEncodingFilter : 解决 post 请求中文乱码的问题。
在 SpringMVC 框架, 需要在 web.xml 注册过滤器并配置其相关属性。
在SpringBoot 中使用字符集过滤器解决 post 请求乱码有两种方式:
使用示例:

  • 创建 SpringBoot 项目,选择 Spring Web 依赖,整理项目目录和 pom 文件,刷新 pom
  • 创建自定义 servlet,处理请求
    1. public class MyServlet extends HttpServlet {
    2.     @Override
    3.     protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    4.         response.setContentType("text/html"); // 此处并没有设置字符编码方式
    5.         PrintWriter out = response.getWriter();
    6.         out.write("没有设置编码方式,默认使用ISO-8859-1,会出现中文乱码");
    7.         out.flush();
    8.         out.close();
    9.     }
    10. }
    复制代码
  • 创建自定义配置类,注册 servlet,设置访问路径
    1. @Configuration
    2. public class WebSystemConfig {
    3.     // 注册servlet,设置访问路径
    4.     @Bean
    5.     public ServletRegistrationBean servletRegistrationBean() {
    6.         ServletRegistrationBean bean = new ServletRegistrationBean();
    7.         bean.setServlet(new MyServlet());
    8.         bean.addUrlMappings("/myservlet");
    9.         return bean;
    10.     }
    11. }
    复制代码
  • 启动主程序,输入访问地址进行测试
    1. http://localhost:8080/myservlet
    2. 结果:出现中文乱码
    3. ?????????????ISO-8859-1????????
    复制代码
方式一:配置类中设置字符编码(不推荐)

不仅需要在配置类中注册字符集过滤器类,设置字符编码,还需在配置文件中关闭默认启用的过滤器。

  • 在自定义配置类中需创建指定返回值类型的方法,注册 CharacterEncodingFilter字符集过滤器类,设置字符编码
  1. @Configuration
  2. public class WebSystemConfig {
  3.     // 注册servlet,设置访问路径
  4.     @Bean
  5.     public ServletRegistrationBean servletRegistrationBean() {
  6.         ServletRegistrationBean bean = new ServletRegistrationBean();
  7.         bean.setServlet(new MyServlet());
  8.         bean.addUrlMappings("/myservlet");
  9.         return bean;
  10.     }
  11.     // ==================================================================
  12.     // 注册CharacterEncodingFilter,并设置字符编码方式
  13.     @Bean
  14.     public FilterRegistrationBean filterRegistrationBean() {
  15.         FilterRegistrationBean reg = new FilterRegistrationBean();
  16.         CharacterEncodingFilter filter = new CharacterEncodingFilter();
  17.         // 设置字符编码方式
  18.         filter.setEncoding("UTF-8");
  19.         // 指定request,response都使用encoding的值
  20.         filter.setForceEncoding(true);
  21.         reg.setFilter(filter); // 注册字符集过滤器对象CharacterEncodingFilter
  22.         reg.addUrlPatterns("/*"); // 设置过滤地址
  23.         return reg;
  24.     }
  25.     // ==================================================================   
  26. }
复制代码

  • 修改 application.properties 文件,让自定义的过滤器起作用
    1. #SpringBoot中默认已经配置了CharacterEncodingFilter。 编码默认ISO-8859-1
    2. #设置enabled=false 作用是关闭系统中配置好的过滤器, 使用自定义的CharacterEncodingFilter
    3. server.servlet.encoding.enabled=false
    复制代码
方式二:配置文件中设置字符编码(推荐)

只需要通过几行配置,即可完成字符编码的设置。
  1. #让系统的CharacterEncdoingFilter生效(默认为true)
  2. server.servlet.encoding.enabled=true
  3. #指定使用的编码方式
  4. server.servlet.encoding.charset=UTF-8
  5. #强制request,response都使用charset属性的值
  6. server.servlet.encoding.force=true
复制代码
ORM 操作 MySQL

ORM 是“对象-关系-映射”的简称。(Object Relational Mapping,简称ORM)
使用 MyBatis 框架操作 MySQL。
使用 MyBatis 框架操作数据,使用 SpringBoot 框架集成 MyBatis。
SpringBoot 集成 Mybatis

以下是集成步骤示例,创建 dao 接口的代理对象有好几种方式可供选择,以下方式并不完美,注意后续自己修改!
  1. 前期准备
  2. 数据库名:springdb
  3. 数据库表:student
  4. 字段:id (int auto_increment) name(varchar) age(int)
复制代码
步骤:

  • 创建 SpringBoot 项目,添加 Spring Web、MyBatis、MySQL 依赖,整理项目目录和 pom 文件,刷新 pom
  • 创建实体类 model
    1. public class Student {
    2.     private Integer id;
    3.     private String name;
    4.     private Integer age;
    5.     // getter,setter,toString...
    6. }   
    复制代码
  • 写 dao 接口和 mapper 文件
    此处 dao 接口上使用了 @Mapper注解,告诉MyBatis这是 dao 接口,创建此接口的代理对象
    1. @Mapper  // 告诉MyBatis这是dao接口,创建此接口的代理对象
    2. public interface StudentDao {
    3.     Student selectById(@Param("stuId") Integer id);
    4. }
    复制代码
    1. <?xml version="1.0" encoding="UTF-8" ?>
    2. <!DOCTYPE mapper
    3.         PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    4.         "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    5. <mapper namespace="com.luis.dao.StudentDao">
    6.     <select id="selectById" resultType="com.luis.model.Student">
    7.         select id,name,age from student where id=#{stuId}
    8.   </select>
    9. </mapper>
    复制代码
  • 创建 service 接口及其实现类
    1. // 接口
    2. public interface StudentService {
    3.     Student queryStudentById(Integer id);
    4. }
    5. // 实现类
    6. @Service
    7. public class StudentServiceImpl implements StudentService {
    8.     @Resource
    9.     private StudentDao studentDao;
    10.     @Override
    11.     public Student queryStudentById(Integer id) {
    12.         return studentDao.selectById(id);
    13.     }
    14. }
    复制代码
  • 创建控制器类
    1. @Controller
    2. @RequestMapping("/student")
    3. public class StudentController {
    4.    
    5.     @Resource
    6.     private StudentService studentService;
    7.     @RequestMapping("/queryById")
    8.     @ResponseBody
    9.     public String queryStudentById(Integer id) {
    10.         Student student = studentService.queryStudentById(id);
    11.         return student.toString();
    12.     }
    13. }
    复制代码
  • 在 pom 文件的 build 标签下添加 mapper 文件的 resources 插件
    1. <resources>
    2.     <resource>
    3.         <directory>src/main/java</directory>
    4.         <includes>
    5.             <include>**/*.xml</include>
    6.         </includes>
    7.     </resource>
    复制代码
  • 在主配置文件中配置端口,上下文访问路径,数据库连接等信息
    1. server.port=8888
    2. server.servlet.context-path=/orm
    3. #配置数据库连接信息 注意mysql新旧版本配置不同
    4. spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
    5. spring.datasource.url=jdbc:mysql://localhost:3306/springdb?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8
    6. spring.datasource.username=root
    7. spring.datasource.password=luis
    复制代码
  • 运行启动类,输入访问地址测试【注意:填的id必须数据库中有,否则会出现空指针异常】
    1. http://localhost:8888/orm/student/queryById?id=29
    复制代码
日志配置

在主配置文件中配置 mybatis 日志:(可选不同的日志打印,如选 log4j 这种的,则另需添加相关依赖)
  1. # 日志配置
  2. mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
复制代码
第一种方式:使用@Mapper(不建议)


  • 使用在类上
  • 作用:告诉 MyBatis 这是 dao 接口,会自动创建此接口的代理对象
  • 缺点:每一个需要创建代理对象的 dao 接口都需要加上该注解,dao 接口多的时候不方便!
示例:
  1. @Mapper  // 告诉MyBatis这是dao接口,创建此接口的代理对象
  2. public interface StudentDao {
  3.     Student selectById(@Param("stuId") Integer id);
  4. }
复制代码
第二种方式:使用@MapperScan


  • 通常使用在主启动类上
  • basePackages属性:通常配置 dao 接口所在包名
  • 作用:找到 Dao 接口以及 Mapper 文件(可直接扫描到该包下所有的 dao 接口和 mapper 文件)
  • 优点:使用该注解直接扫描指定包,不用在每一个 dao 接口上分别加 @Mapper注解
示例:
  1. @SpringBootApplication
  2. @MapperScan(basePackages = "com.luis.dao") // 扫描指定包,找到dao接口和mapper文件,mybatis自动创建接口的代理对象
  3. public class SpringbootMapperApplication {
  4.     public static void main(String[] args) {
  5.         SpringApplication.run(SpringbootMapperApplication.class, args);
  6.     }
  7. }
复制代码
第三种方式:Mapper文件和Dao接口分开管理(开发常用,推荐使用)

之前我们的 dao 目录下既有 Java 文件,也有 xml/mapper 文件;如果希望 Java 目录下只有 Java 文件,将 xml/mapper 文件放到 resources 下分开管理,那么只使用之前的 @MapperScan注解是扫描不到 resources 下的 Mapper 文件的,此时我们就需要在配置文件中指定 Mapper 文件的位置。
示例:
操作:在 resources 下创建子目录(自定义的),例如 mapper,用来存放 mapper 映射文件,将之前 dao 下的 mapper 文件全剪切到 mapper 目录下。

  • 同样,我们仍然需要在主启动类上使用 @MapperScan注解指定 dao 所在的包,扫描 dao 接口:
  1. @SpringBootApplication
  2. @MapperScan(basePackages = "com.luis.dao") // 扫描指定包,找到dao接口和mapper文件,mybatis自动创建接口的代理对象
  3. public class SpringbootMapperApplication {
  4.     public static void main(String[] args) {
  5.         SpringApplication.run(SpringbootMapperApplication.class, args);
  6.     }
  7. }
复制代码

  • 在主配置文件中指定 mapper 映射文件的位置:
  1. #指定mapper文件的位置
  2. mybatis.mapper-locations=classpath:mapper/*.xml
复制代码

  • 配置资源插件,确保资源文件编译到 classes 目录下:
  1. <resources>
  2.     <resource>
  3.         <directory>src/main/resources</directory>
  4.         <includes>
  5.             <include>**/*.*</include>
  6.         </includes>
  7.     </resource>
  8. </resources>
复制代码
注意:如果项目编译后 .xml/properties/yml 文件没有出现在 classes 目录下,则需要在 pom 中添加 resources 资源插件。
事务及mybatis自动代码生成器的使用

回顾 Spring 框架中的事务:

  • 管理事务的对象:事务管理器(接口,接口有很多的实现类)
    例如:使用 Jdbc 或 mybatis 访问数据库,使用的事务管理器:DataSourceTransactionManager
  • 声明式事务:使用 xml 配置文件或者使用注解说明事务控制的内容
    控制事务:隔离级别,传播行为,超时时间
  • 事务处理方式:

    • Spring 框架中的 @Transactional
    • Spring 支持 aspectj 框架的事务配置,可在 xml 配置文件中,声明事务控制的内容

SpringBoot 中使用事务:上面的两种方式都可以。
使用步骤:(以下以注解方式演示事务的使用:)

  • 在业务方法的上面加入 @Transactional ,加注解后,方法就有事务功能
  • 明确的在主启动类的上面,加入@EnableTransactionManager,启用事务管理器(可不用添加此注解)
  1. /**
  2.      * @Transactional 表示方法有事务支持,抛出运行时异常,则进行回滚
  3.      * 使用MySQL默认的传播行为、隔离级别、超时时间
  4.      */
  5. @Transactional // 可通过属性配置传播行为、隔离级别、超时时间
  6. @Override
  7. public int addUser(User user) {
  8.     System.out.println("业务方法addUser开始执行");
  9.     int rows = userMapper.insert(user);
  10.     System.out.println("业务方法addUser结束执行");
  11.     // 模拟发生运行时异常
  12.     // int num = 10 / 0;
  13.     return rows;
  14. }
复制代码
SpringBoot 中通过注解使用事务,一句话说明:直接在需要开启事务的业务方法上添加 @Transactional 注解即可!
示例:(有mybatis自动代码生成器的使用示例,可自动生成 model 实体类, dao 接口以及 mapper 映射文件)
  1. 准备数据库表:
  2. 数据库名:springdb 表名:user
  3. 字段:id(int auto_increment)name(varchar)age(int)
复制代码

  • 创建 SpringBoot 项目,添加 Spring Web、MyBatis、MySQL 依赖,整理项目目录和 pom 文件
  • 在 pom 的 plugins 标签下添加 mybatis 自动代码生成插件
    1. <plugin>
    2.     <groupId>org.mybatis.generator</groupId>
    3.     <artifactId>mybatis-generator-maven-plugin</artifactId>
    4.     <version>1.3.6</version>
    5.     <configuration>
    6.         
    7.         <configurationFile>GeneratorMapper.xml</configurationFile>
    8.         <verbose>true</verbose>
    9.         <overwrite>true</overwrite>
    10.     </configuration>
    11. </plugin>
    复制代码
  • 在 pom 的 build 标签下添加资源插件,处理资源文件,刷新 pom
    1. <resources>
    2.     <resource>
    3.         <directory>src/main/resources</directory>
    4.         <includes>
    5.             <include>**/**.*</include>
    6.         </includes>
    7.     </resource>
    8. </resources>
    复制代码
  • 在项目根目录下创建 GeneratorMapper.xml文件,其与 src 平级;将下列内容拷贝到文件中;依照注释修改配置,修改完后,点开右侧 maven 快捷窗口,使用当前项目下 plugins 下 mybatis-genetate 下的 mybatis 自动代码生成插件进行生成。
    1. <?xml version="1.0" encoding="UTF-8"?>
    2. <!DOCTYPE generatorConfiguration
    3.         PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
    4.         "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
    5. <generatorConfiguration>
    6.    
    7.     <classPathEntry location="D:\Java\tools\mysql-connector-java-8.0.28.jar"/>
    8.    
    9.     <context id="tables" targetRuntime="MyBatis3">
    10.         
    11.         <commentGenerator>
    12.             <property name="suppressAllComments" value="true" />
    13.         </commentGenerator>
    14.         
    15.         <jdbcConnection driver
    16.                         connectionURL="jdbc:mysql://localhost:3306/springdb?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8"
    17.                         userId="root"
    18.                         password="luis">
    19.             
    20.             
    21.             <property name="nullCatalogMeansCurrent" value="true" />
    22.         </jdbcConnection>
    23.         
    24.         <javaModelGenerator targetPackage="com.luis.model"
    25.                             targetProject="D:\1a-Projects\springboot-projects\springboot-transactional\src\main\java">
    26.             <property name="enableSubPackages" value="false" />
    27.             <property name="trimStrings" value="false" />
    28.         </javaModelGenerator>
    29.         
    30.         <sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources">
    31.             <property name="enableSubPackages" value="false" />
    32.         </sqlMapGenerator>
    33.         
    34.         <javaClientGenerator type="XMLMAPPER" targetPackage="com.luis.dao" targetProject="src/main/java">
    35.             <property name="enableSubPackages" value="false" />
    36.         </javaClientGenerator>
    37.         
    38.         <table tableName="user" domainObjectName="User"
    39.                enableCountByExample="false"
    40.                enableUpdateByExample="false"
    41.                enableDeleteByExample="false"
    42.                enableSelectByExample="false"
    43.                selectByExampleQueryId="false"/>
    44.         <table tableName="b_bid_info" domainObjectName="BidInfo"
    45.                enableCountByExample="false"
    46.                enableUpdateByExample="false"
    47.                enableDeleteByExample="false"
    48.                enableSelectByExample="false"
    49.                selectByExampleQueryId="false"/>
    50.         <table tableName="b_income_record" domainObjectName="IncomeRecord"
    51.                enableCountByExample="false"
    52.                enableUpdateByExample="false"
    53.                enableDeleteByExample="false"
    54.                enableSelectByExample="false"
    55.                selectByExampleQueryId="false"/>
    56.         <table tableName="b_recharge_record" domainObjectName="RechargeRecord"
    57.                enableCountByExample="false"
    58.                enableUpdateByExample="false"
    59.                enableDeleteByExample="false"
    60.                enableSelectByExample="false"
    61.                selectByExampleQueryId="false"/>
    62.         <table tableName="u_user" domainObjectName="User"
    63.                enableCountByExample="false"
    64.                enableUpdateByExample="false"
    65.                enableDeleteByExample="false"
    66.                enableSelectByExample="false"
    67.                selectByExampleQueryId="false"/>
    68.         <table tableName="u_finance_account" domainObjectName="FinanceAccount"
    69.                enableCountByExample="false"
    70.                enableUpdateByExample="false"
    71.                enableDeleteByExample="false"
    72.                enableSelectByExample="false"
    73.                selectByExampleQueryId="false"/>
    74.     </context>
    75. </generatorConfiguration>
    复制代码
  • 主配置文件配置
    1. #配置端口
    2. server.port=9090
    3. #context-path
    4. server.servlet.context-path=/mytrans
    5. #数据库连接配置
    6. spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
    7. spring.datasource.url=jdbc:mysql://localhost:3306/springdb?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8
    8. spring.datasource.username=root
    9. spring.datasource.password=luis
    10. #配置mapper文件路径
    11. mybatis.mapper-locations=classpath:mapper/*.xml
    12. #开启日志
    13. mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
    复制代码
  • 使用 mybatis 生成器生成的 model、dao、mapper 文件
    1. // model
    2. public class User {
    3.     private Integer id;
    4.     private String name;
    5.     private Integer age;
    6.     // get,set
    7. }
    8. // dao
    9. public interface UserMapper {
    10.     int deleteByPrimaryKey(Integer id);
    11.     int insert(User record);
    12.     int insertSelective(User record);
    13.     User selectByPrimaryKey(Integer id);
    14.     int updateByPrimaryKeySelective(User record);
    15.     int updateByPrimaryKey(User record);
    16. }
    复制代码
    1. <?xml version="1.0" encoding="UTF-8"?>
    2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    3. <mapper namespace="com.luis.dao.UserMapper">
    4.     <resultMap id="BaseResultMap" type="com.luis.model.User">
    5.         <id column="id" jdbcType="INTEGER" property="id" />
    6.         <result column="name" jdbcType="VARCHAR" property="name" />
    7.         <result column="age" jdbcType="INTEGER" property="age" />
    8.     </resultMap>
    9.     <sql id="Base_Column_List">
    10.         id, name, age
    11.     </sql>
    12.     <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
    13.         select
    14.         <include refid="Base_Column_List" />
    15.         from user
    16.         where id = #{id,jdbcType=INTEGER}
    17.     </select>
    18.     <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
    19.         delete from user
    20.         where id = #{id,jdbcType=INTEGER}
    21.     </delete>
    22.     <insert id="insert" parameterType="com.luis.model.User">
    23.         insert into user (id, name, age
    24.         )
    25.         values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER}
    26.         )
    27.     </insert>
    28.     <insert id="insertSelective" parameterType="com.luis.model.User">
    29.         insert into user
    30.         <trim prefix="(" suffix=")" suffixOverrides=",">
    31.             <if test="id != null">
    32.                 id,
    33.             </if>
    34.             <if test="name != null">
    35.                 name,
    36.             </if>
    37.             <if test="age != null">
    38.                 age,
    39.             </if>
    40.         </trim>
    41.         <trim prefix="values (" suffix=")" suffixOverrides=",">
    42.             <if test="id != null">
    43.                 #{id,jdbcType=INTEGER},
    44.             </if>
    45.             <if test="name != null">
    46.                 #{name,jdbcType=VARCHAR},
    47.             </if>
    48.             <if test="age != null">
    49.                 #{age,jdbcType=INTEGER},
    50.             </if>
    51.         </trim>
    52.     </insert>
    53.     <update id="updateByPrimaryKeySelective" parameterType="com.luis.model.User">
    54.         update user
    55.         <set>
    56.             <if test="name != null">
    57.                 name = #{name,jdbcType=VARCHAR},
    58.             </if>
    59.             <if test="age != null">
    60.                 age = #{age,jdbcType=INTEGER},
    61.             </if>
    62.         </set>
    63.         where id = #{id,jdbcType=INTEGER}
    64.     </update>
    65.     <update id="updateByPrimaryKey" parameterType="com.luis.model.User">
    66.         update user
    67.         set name = #{name,jdbcType=VARCHAR},
    68.         age = #{age,jdbcType=INTEGER}
    69.         where id = #{id,jdbcType=INTEGER}
    70.     </update>
    71. </mapper>
    复制代码
  • 创建 service 接口及其实现类,在实现类的业务方法上添加 @Transactional注解,开启事务支持
    1. public interface UserService {
    2.     int addUser(User user);
    3. }
    4. @Service
    5. public class UserServiceImpl implements UserService {
    6.     @Resource
    7.     private UserMapper userMapper;
    8.     /**
    9.      * @Transactional 表示方法有事务支持,抛出运行时异常,则进行回滚
    10.      * 使用MySQL默认的传播行为、隔离级别、超时时间
    11.      */
    12.     @Transactional
    13.     @Override
    14.     public int addUser(User user) {
    15.         System.out.println("业务方法addUser开始执行");
    16.         int rows = userMapper.insert(user);
    17.         System.out.println("业务方法addUser结束执行");
    18.         // 模拟发生运行时异常
    19.         int num = 10 / 0; // 测试时通过注释以及放开观察事务控制
    20.         return rows;
    21.     }
    22. }
    复制代码
  • 创建控制器类
    1. @Controller
    2. public class UserController {
    3.    
    4.     @Resource
    5.     private UserService userService;
    6.     @RequestMapping("/addStudent")
    7.     @ResponseBody
    8.     public String addStudent(String name, Integer age) {
    9.         User user = new User();
    10.         user.setName(name);
    11.         user.setAge(age);
    12.         int rows = userService.addUser(user);
    13.         return "添加结果:" + rows;
    14.     }
    15. }
    复制代码
  • 主启动类上添加@EnableTransactionManagement注解,启用事务管理器,与业务方法上的@Transactional配套使用;继续在主启动类上添加@MapperScan注解,指定dao所在的包,扫描dao包下dao接口和mapper文件。
    1. @SpringBootApplication
    2. @EnableTransactionManagement // 启用事务管理器,与业务方法上的@Transactional一起使用
    3. @MapperScan(basePackages = "com.luis.dao") // 指定dao所在的包,扫描dao包下dao接口和mapper文件
    4. public class SpringbootTransactionalApplication {
    5.     public static void main(String[] args) {
    6.         SpringApplication.run(SpringbootTransactionalApplication.class, args);
    7.     }
    8. }
    复制代码
  • 运行主启动类,浏览器输入访问地址;配合业务方法中设置的运行时异常(分别注释和放开),观察访问结果以及数据库表中数据变化进行测试
    1. http://localhost:9090/mytrans/addUser?name=luis&age=5
    2. 测试结果:发生运行时异常,进行了事务回滚,数据操作撤销,但主键会自增;无运行时异常,数据添加成功
    3. 结论:该业务方法支持了事务
    复制代码
接口架构风格——RESTful

接口的概念



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

前后端分离的思想:前端从后端剥离,形成一个前端工程,前端只利用Json来和后端进行交互,后端不返回页面,只返回Json数据。前后端之间完全通过public API约定。
前后端分离(解耦)的核心思想是:前端Html页面通过Ajax调用后端的RestFul API并使用Json数据进行交互。
注: 【在互联网架构中,web服务器:一般指像nginx,apache这类的服务器,他们一般只能解析静态资源。应用服务器:一般指像tomcat,jetty,resin这类的服务器可以解析动态资源也可以解析静态资源,但解析静态资源的能力没有web服务器好。】
一般只有Web服务器才能被外网访问,应用服务器只能内网访问。
————————————————
版权声明:本文为CSDN博主「山河远阔」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_37539378/article/details/79956760
前后端分离并非仅仅只是一种开发模式,而是一种架构模式(前后端分离架构)。
千万不要以为只有在撸代码的时候把前端和后端分开就是前后端分离了,需要区分前后端项目!
前端项目与后端项目是两个项目,放在两个不同的服务器,需要独立部署,两个不同的工程,两个不同的代码库,不同的开发人员。
前后端工程师需要约定交互接口,实现并行开发,开发结束后需要进行独立部署,前端通过ajax来调用http请求调用后端的restful api。
前端只需要关注页面的样式与动态数据的解析&渲染,而后端专注于具体业务逻辑。
————————————————下面原文很有阅读价值!
版权声明:本文为CSDN博主「山河远阔」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_37539378/article/details/79956760
REST 介绍



  • REST (英文:Representational State Transfer ,简称  REST;中文: 表现层状态转移 )
  • 一种互联网软件架构设计的风格,但它并不是标准,它只是提出了一组客户端和服务器交互时的架构理念和设计原则,基于这种理念和原则设计的接口可以更简洁,更有层次。
  • 任何的技术都可以实现这种理念,如果一个架构符合 REST 原则,就称它为 RESTFul 架构。
比如我们要访问一个 http 接口:http://localhost:8080/boot/order?id=1021&status=1
采用 RESTFul 风格则 http 地址为:http://localhost:8080/boot/order/1021/1
表现层状态转移::

  • 表现层就是视图层,显示资源的,通过视图页面,jsp 等等显示操作资源的结果。
  • 状态: 资源变化
  • 转移:资源是可以变化的。资源能创建,new 状态,资源创建后可以查询资源,能看到资源的内容,这个资源内容,可以被修改,修改后,资源和之前的不一样。
REST中的要素:

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


  • 轻量,直接基于 http,不再需要任何别的诸如消息协议
    get/post/put/delete 为 CRUD 操作
  • 面向资源,一目了然,具有自解释性。
  • 数据描述简单,一般以 xml,json 做数据交换。
  • 无状态,在调用一个接口(访问、操作资源)的时候,可以不用考虑上下文,不用考虑当前状态,
    极大的降低了复杂度。
  • 简单、低耦合
REST 操作资源

方式:使用 http 中不同动作(请求方式)表示对资源的不同操作(CURD)
示例:

  • GET:查询资源  --  sql select
​                 处理单个资源:用其单数方式
​                  http://localhost:8080/myboot/student/1001
​                 http://localhost:8080/myboot/student/1001/1
​                处理多个资源:使用复数形式
​                  http://localhost:8080/myboot/students/1001/1002

  • POST:创建资源  -- sql insert
​                http://localhost:8080/myboot/student
​                在post请求中传递数据
  1. <form action="http://localhost:8080/myboot/student" method="post">
  2.     姓名:<input type="text" name="name" />
  3.     年龄:<input type="text" name="age" />
  4. </form>
复制代码

  • PUT: 更新资源  --  sql  update
  1. <form action="http://localhost:8080/myboot/student" method="post">
  2.     姓名:<input type="text" name="name" />
  3.     年龄:<input type="text" name="age" />
  4. </form>   
复制代码

  • DELETE: 删除资源  -- sql delete
  1. <a target="_blank" href="http://localhost:8080/myboot/student/1">删除1的数据</a>
复制代码
需要的分页,排序等参数,依然放在 url 的后面,例如
http://localhost:8080/myboot/students?page=1&pageSize=20
SpringBoot 开发 RESTful

SpringBoot 开发 RESTful 主要是通过以下几个注解实现:

  • @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:一个复合注解,是@Controller和 @ResponseBody的组合。
    在类的上面使用@RestController,表示当前类的所有方法都加入了@ResponseBody
使用示例:

  • 创建 SpringBoot 项目,选择 Spring Web 依赖,整理 pom 文件,刷新 pom
  • 创建控制器类,使用相关注解
    1. /**
    2. * @RestController:复合注解,包含@Controller和@ResponseBody
    3. *      控制器类上加上此注解,则类中所有方法都是返回对象数据
    4. */
    5. @RestController
    6. public class MyRestController {
    7.     /**
    8.      * @GetMapping:接收get请求
    9.      * @PathVariable(路径变量):获取url中数据
    10.      *      使用位置:控制器方法的形参前
    11.      *      注解的属性value:路径变量名
    12.      * 注意:当@PathVariable的路径变量名value与形参名相同时,属性value值可以省略
    13.      * 查询资源:使用GET请求方式
    14.      * http://localhost:9999/myboot/student/1002
    15.      */
    16.     @GetMapping("/student/{stuId}") // 接收get请求
    17.     public String queryStudent(@PathVariable("stuId") Integer studentId) {
    18.         return "查询的学生id:" + studentId;
    19.     }
    20. }
    复制代码
  • 主配置文件中配置端口和上下文路径
    1. server.port=9999
    2. server.servlet.context-path=/myboot
    复制代码
  • 运行主启动类,浏览器输入访问地址进行测试
    1. http://localhost:9999/myboot/student/1002
    复制代码
基于以上,进行其他请求测试:
控制器类中添加 post 请求处理方法:
  1. /**
  2.      * 创建资源:使用POST请求方式
  3.      * http://localhost:9999/myboot/student/luis/22
  4.      * 注意:当@PathVariable的路径变量名value与形参名相同时,属性value值可以省略
  5.      */
  6. @PostMapping("/student/{name}/{age}") // 接收post请求
  7. public String addStudent(@PathVariable String name,
  8.                          @PathVariable Integer age) {
  9.     return "创建student信息:" + name + " " + age;
  10. }
复制代码
在 resources/static 下创建 addStudent.html 页面发送 post 请求:
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4.     <meta charset="UTF-8">
  5.     <title>post请求创建资源</title>
  6. </head>
  7. <body>
  8.     <p>创建学生信息</p>
  9.     <form action="student/luis/22" method="post">
  10.         <input type="submit" value="提交post创建学生信息">
  11.     </form>
  12. </body>
  13. </html>
复制代码
运行主启动类,先访问页面,在页面上发送 post 请求:
  1. http://localhost:9999/myboot/addStudent.html
复制代码
可以发现,开发中模拟各种 post 请求,都需要自己创建表单页面,十分不便!
可以使用 Postman 工具,可模拟发送各种请求,使用王妈妈提供的汉化版本,免安装,免登陆!
控制器类中分别创建更新资源和删除资源的处理方法,启动项目,在 Postman 上进行访问测试:
  1. /**
  2.      * 修改资源:使用PUT请求方式,浏览器使用POST处理PUT请求
  3.      * http://localhost:9999/myboot/student/luis/24
  4.      * 注意:当@PathVariable的路径变量名value与形参名相同时,属性value值可以省略
  5.      */
  6. @PutMapping("/student/{name}/{age}") // 修改资源使用@PutMapping
  7. public String modifyStudent(@PathVariable String name,
  8.                             @PathVariable Integer age) {
  9.     return "修改信息:" + name + " " + age;
  10. }
  11. /**
  12.      * 删除资源:使用DELETE请求方式,浏览器使用POST处理DELETE请求
  13.      * http://localhost:9999/myboot/student/3
  14.      * 注意:当@PathVariable的路径变量名value与形参名相同时,属性value值可以省略
  15.      */
  16. @DeleteMapping("/student/{id}")
  17. public String removeStudentById(@PathVariable Integer id) {
  18.     return "删除信息:id = " + id;
  19. }
复制代码
在页面或ajax中支持put和delete请求

浏览器是不支持 PUT 和 DELETE 请求的,只支持 GET 和 POST;即在表单中只支持 get 和 post!
在 SpringMVC 中有一个过滤器,支持 post 请求转为 put 和 delete
过滤器:org.springframework.web.filter.HiddenHttpMethodFilter
作用:把请求中的 post 请求转为 put 或 delete
使用说明:在表单中想发送 put 或 delete 请求,需配置请求方式为 post,然后在表单的隐藏域标签中指定name=_method,value=put/delete;在 SpringBoot 的配置文件中启用 SpringMVC 的过滤器后,会自动将 post 请求转为指定的 put 或 delete。
实现步骤:

  • application.properties(yml) 开启使用 HiddenHttpMethodFilter 过滤器
    1. #启用过滤器,支持put和delete请求
    2. spring.mvc.hiddenmethod.filter.enabled=true
    复制代码
  • 在请求页面中,包含 _method 参数,其值是 put 或 delete,发起这个请求需使用 post 方式
    1. <!DOCTYPE html>
    2. <html lang="en">
    3. <head>
    4.     <meta charset="UTF-8">
    5.     <title>测试表单提交方式</title>
    6. </head>
    7. <body>
    8.     <form action="student/test" method="post">
    9.         
    10.         <input type="hidden" name="_method" value="put"/>
    11.         <input type="submit" value="表单提交put请求"/>
    12.     </form>
    13.     <form action="student/test" method="post">
    14.         
    15.         <input type="hidden" name="_method" value="delete"/>
    16.         <input type="submit" value="表单提交delete请求"/>
    17.     </form>
    18. </body>
    19. </html>
    复制代码
附控制器测试方法:
  1. @RestController
  2. public class MyRestController {
  3.     @PutMapping("/student/test")
  4.     public String testPut() {
  5.         return "put请求成功";
  6.     }
  7.     @DeleteMapping("/student/test")
  8.     public String testDelete() {
  9.         return "delete请求成功";
  10.     }
  11. }
复制代码
使用REST注意

使用 REST 注意,必须保证请求地址 URL 加上请求方式唯一,不然会出现冲突。
如下面两个请求处理方法,在请求时就会出现冲突,无法确定用哪个方法处理请求!
  1. @GetMapping("/student/{id}")
  2. public String queryId(@PathVariable Integer id) {
  3.     return "查询的学生id:" + id;
  4. }
  5. @GetMapping("/student/{age}")
  6. public String queryAge(@PathVariable Integer age) {
  7.     return "查询的学生age:" + age;
  8. }
复制代码
SpringBoot 集成 Redis


  • Redis:一个NoSQL数据库,常用作缓存使用(cache)
  • Redis 的五种数据类型:string、hash、set、zset、list
  • Redis 是一个中间件,是一个独立的服务器。
  • Java 中著名的客户端:Jedis,lettuce,Redisson
SpringBoot 中有 RedisTemplate 和 StringRedisTemplate,都可以处理和 redis 的数据交互。
PS:其实使用的 RedisTemplate,其底层还是调用的 lettuce 客户端方法来处理数据。
配置 Windows 版本的 redis

临时性使用 redis ,可直接在 Windows 上使用解压后的安装包,启动服务端和客户端即可!(网盘有压缩包,解压即可使用)
Redis-x64-3.2.100.rar 解压缩到一个非中文的目录
redis-server.exe:服务端,启动后,不要关闭
redis-cli.exe:客户端,访问 redis 中的数据
redisclient-win32.x86_64.2.0.jar:Redis 的一个图形界面客户端
执行方式:在这个文件所在的目录,执行 java -jar redisclient-win32.x86_64.2.0.jar 即可
SpringBoot 集成 Redis

步骤:

  • 创建 SpringBoot 项目,选择 Spring Web 和 Redis 依赖,整理 pom 并刷新
  • application.properties/yml 中配置连接 redis 的相关参数
    1. server.port=7777
    2. server.servlet.context-path=/myredis
    3. #配置redis:host ip password
    4. spring.redis.host=localhost
    5. spring.redis.port=6379
    6. #spring.redis.password=123
    复制代码
  • 创建控制器类,创建请求处理方法,获取操作 redis 数据的对象,处理数据交互
    1. @RestController
    2. public class RedisController {
    3.     /**
    4.      * 注入RedisTemplate(处理和redis的数据交互)
    5.      * 其默认使用的jdk序列化,可读性差(查看数据库中数据有类似乱码问题)
    6.      * 三种泛型情况:
    7.      *      RedisTemplate<String,String>
    8.      *      RedisTemplate<Object,Object>
    9.      *      RedisTemplate
    10.      */
    11.     @Resource
    12.     private RedisTemplate redisTemplate;
    13.     /**
    14.      * 注入StringRedisTemplate(处理和redis的数据交互)
    15.      * 其默认使用的String序列化,可读性好(数据库中数据正常显示)
    16.      */
    17.     @Resource
    18.     private StringRedisTemplate stringRedisTemplate;
    19.     @PostMapping("/redis/addstring")
    20.     public String addToRedis(String key, String value) { // 使用传统风格
    21.         // 添加数据到redis(使用RedisTemplate对象)
    22.         ValueOperations valueOperations = redisTemplate.opsForValue(); // 获取redis中操作string类型数据的对象
    23.         valueOperations.set(key, value);
    24.         return "成功添加数据到redis";
    25.     }
    26.     @GetMapping("/redis/getstring")
    27.     public String getKFromRedis(String key) { // 使用传统风格
    28.         // 从redis获取数据(使用RedisTemplate对象)
    29.         ValueOperations valueOperations = redisTemplate.opsForValue(); // 获取redis中操作string类型数据的对象
    30.         Object o = valueOperations.get(key);
    31.         return key + " = " + key + ", value = " + o;
    32.     }
    33.     @PostMapping("/redis/{k}/{v}")
    34.     public String addStringKV(@PathVariable String k,
    35.                               @PathVariable String v) { // 使用RESTful风格
    36.         // 添加数据到redis(使用StringRedisTemplate对象)
    37.         ValueOperations<String, String> stringStringValueOperations = stringRedisTemplate.opsForValue();
    38.         stringStringValueOperations.set(k, v);
    39.         return "成功添加数据到redis";
    40.     }
    41.     @GetMapping("/redis/{k}")
    42.     public String getK(@PathVariable String k) { // 使用RESTful风格
    43.         // 从redis获取数据(使用StringRedisTemplate对象)
    44.         ValueOperations<String, String> stringStringValueOperations = stringRedisTemplate.opsForValue();
    45.         String v = stringStringValueOperations.get(k);
    46.         return k + " = " + k + ", v = " + v;
    47.     }
    48. }
    复制代码
  • 运行主启动类,使用 Postman 进行请求测试
对比 RedisTemplate 和 StringRedisTemplate


  • StringRedisTemplate:使用的是 String 的序列化方式,把 k,v 都是作为 String 处理,可读性好。
    但是有局限性,只能存 String 类型,且只能是 String 的序列化方式,无法修改为其他的序列化方式。
  • RedisTemplate:默认使用的是 JDK 的序列化方式,把 k,v 经过了 JDK 序列化存到 redis;
    经过了 JDK 序列化的 k,v 在数据库中不能直接识别。
    其默认使用的 jdk 序列化,但可以修改为其他的序列化方式。
    其使用比 StringRedisTemplate 更加广泛,可修改为其他的序列化方式,不仅仅只能存字符串。
序列化概述

序列化和反序列化:

  • 序列化:把对象转化为可传输的字节序列的过程称为序列化。
  • 反序列化:把字节序列还原为对象的过程称为反序列化。
为什么需要序列化?

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

  • 凡是需要进行“跨平台存储”和”网络传输”的数据,都需要进行序列化。
本质上存储和网络传输都需要经过把一个对象状态保存成一种跨平台识别的字节格式,然后其他的平台才可以通过字节信息解析还原对象信息。
序列化的方式:
序列化只是一种拆装和组装对象的规则,这种规则有多种多样,比如现在常见的序列化方式有:
JDK(不支持跨语言)、JSON、XML、Hessian、Kryo(不支持跨语言)、Thrift、Protofbuff 等
例如:
java 的序列化:把 java 对象转为 byte[] 二进制数据
json 的序列化:就是将对象转换为 JSON 字符串格式
json 的反序列化:就是将JSON 字符串格式转换为对象
Student( name=zs, age=20)   ----  { "name":"zs", "age":20 }
设置 RedisTemplate 的序列化方式
  1. @PostMapping("/redis/addData")
  2. public String addData(String k, String v) {
  3.     // 设置key,value均使用String序列化方式(在进行存取值之前设置)
  4.     // 注意,key 和 value 的序列化方式可分别设置
  5.     redisTemplate.setKeySerializer(new StringRedisSerializer());
  6.     redisTemplate.setValueSerializer(new StringRedisSerializer());
  7.     // 获取redis中操作string类型数据的对象
  8.     ValueOperations valueOperations = redisTemplate.opsForValue();
  9.     // 向redis中添加数据
  10.     valueOperations.set(k, v);
  11.     return "设置RedisTemplate序列化方式,并向redis中添加数据";
  12. }
复制代码
设置为 json 序列化方式

设置 json 序列化,存储时把对象转为 json 格式字符串进行存储;获取时将 json 字符串格式转为对象。
如果是 String 序列化方式,则只能存储字符串类型,无法存储对象。
示例:

  • 准备 vo 数据对象 Student(需要进行序列化)
    1. public class Student implements Serializable {
    2.     private static final long serialVersionUID = 684647176563341892L; // 添加后就不要再改动!
    3.     private Integer id;
    4.     private String name;
    5.     private Integer age;
    6.     // getter,setter,toString
    7. }   
    复制代码
  • 写处理请求的处理器方法
    1. @PostMapping("/redis/addjson")
    2. public String addJson() {
    3.     // 准备对象数据
    4.     Student student = new Student();
    5.     student.setId(111);
    6.     student.setName("luis");
    7.     student.setAge(22);
    8.     // 设置key的序列化方式为String(默认的是jdk方式)
    9.     redisTemplate.setKeySerializer(new StringRedisSerializer());
    10.     // 设置value的序列化方式为json(默认的是jdk方式)
    11.     redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer(Student.class));
    12.     // 获取redis中操作string类型数据的对象
    13.     ValueOperations valueOperations = redisTemplate.opsForValue();
    14.     // 向redis中存数据
    15.     // 会依据value设置的json序列化方式自动将Student对象转换为json格式字符串
    16.     valueOperations.set("mystudent", student);
    17.     return "key-string序列化,value-json序列化";
    18. }
    19. @GetMapping("/redis/getjson")
    20. public String getJson() {
    21.     // 设置key的序列化方式为String(默认的是jdk方式)
    22.     redisTemplate.setKeySerializer(new StringRedisSerializer());
    23.     // 设置value的序列化方式为json(默认的是jdk方式)
    24.     redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer(Student.class));
    25.     // 获取redis中操作string类型数据的对象
    26.     ValueOperations valueOperations = redisTemplate.opsForValue();
    27.     // 从redis中获取数据
    28.     // 会依据value设置的json序列化方式自动将json格式字符串转换为Student对象,反序列化回来
    29.     Object o = valueOperations.get("mystudent");
    30.     return "json反序列化:" + o;
    31. }
    复制代码
  • 使用 Postman 发请求测试
小结


  • 临时性使用 redis 或小测试,可直接在 Windows 上使用 redis 的安装包,解压即可使用
  • SpringBoot 中使用 Redis 主要是合理选择 RedisTemplate 或 StringRedisTemplate 来处理和 Redis 的交互
  • 处理单纯的字符串数据,可直接使用 RedisTemplate 对象处理数据交互,其采用 String 序列化方式。
  • 处理对象类型的数据,需要选择 StringRedisTemplate 来处理和 Redis 的交互,其默认采用 JDK 序列化方式;需手动设置改变其序列化方式为 json;还可设置成其他的序列化方式。
  • 数据在网络上传输,或者跨平台传输都需要进行序列化!所以将需要传输的数据,如对象类型的,进行实现序列化接口的操作,并设定序列化版本号!序列化版本号设置后不要再改动!
  • 创建资源使用 POST 请求;获取资源使用 GET 请求;修改资源使用 PUT 请求;删除资源使用 DELETE 请求。
  • 熟悉 Postman 测试工具:熟练选择请求方式、根据传统风格以及 RESTful 风格的快速准确填充数据
SpringBoot 集成 Dubbo

开发中使用 SpringBoot 集成 Dubbo 进行分布式开发!
公共工程负责提供实体 bean 以及业务接口;
服务提供者工程负责实现公共工程中的业务接口,提供并暴露服务,供消费者调用;
服务消费者工程负责调用服务提供者提供的服务。
  1. 需要三个工程:接口工程【java】、服务提供者工程【可web】、服务消费者工程【web】
  2. 接口工程【java】:负责实体 bean 以及业务接口(提供者和消费者均依赖于它)
  3. 服务提供者工程【可web】:负责实现接口工程中的服务接口,提供服务,暴露服务,供消费者调用
  4. 服务消费者工程【web】:负责调用提供者提供的服务   
复制代码
示例:
1.创建接口/公共工程


  • 创建一个 maven 项目,无需选择模板,名为 interface-api(公共的接口工程)
  • 创建 vo 数据类 Student,进行序列化
    1. public class Student implements Serializable {
    2.     private static final long serialVersionUID = -3498691273686241331L;
    3.     private Integer id;
    4.     private String name;
    5.     private Integer age;
    6.     // getter,setter,toString
    7. }   
    复制代码
  • 定义服务接口(业务接口)
    1. public interface StudentService {   
    2.     Student queryStudent(Integer id);
    3. }
    复制代码
2.创建服务提供者工程


  • 创建 SpringBoot 项目,无需添加其他依赖,项目命名 springboot-service-provider(服务提供者工程)
  • 在其 pom 文件中加入公共工程依赖、dubbo 起步依赖和 Zookeeper 依赖,整理 pom,刷新
    1. <dependency>
    2.     <groupId>com.luis</groupId>
    3.     <artifactId>interface-api</artifactId>
    4.     <version>1.0.0</version>
    5. </dependency>
    6. <dependency>
    7.     <groupId>org.apache.dubbo</groupId>
    8.     <artifactId>dubbo-spring-boot-starter</artifactId>
    9.     <version>2.7.8</version>
    10. </dependency>
    11. <dependency>
    12.     <groupId>org.apache.dubbo</groupId>
    13.     <artifactId>dubbo-dependencies-zookeeper</artifactId>
    14.     <version>2.7.8</version>
    15.     <type>pom</type>
    16.     <exclusions>
    17.         
    18.         <exclusion>
    19.             <artifactId>slf4j-log4j12</artifactId>
    20.             <groupId>org.slf4j</groupId>
    21.         </exclusion>
    22.     </exclusions>
    23. </dependency>
    复制代码
    注意:服务提供者中如果要使用到redis,并涉及json序列化操作,在不添加web起步依赖下,必须加下列jackson依赖!
    1. <dependency>
    2.     <groupId>com.fasterxml.jackson.core</groupId>
    3.     <artifactId>jackson-databind</artifactId>
    4.     <version>2.13.2.2</version>
    5. </dependency>
    6. <dependency>
    7.     <groupId>com.fasterxml.jackson.datatype</groupId>
    8.     <artifactId>jackson-datatype-jdk8</artifactId>
    9.     <version>2.13.2</version>
    10. </dependency>
    11. <dependency>
    12.     <groupId>com.fasterxml.jackson.datatype</groupId>
    13.     <artifactId>jackson-datatype-jsr310</artifactId>
    14.     <version>2.13.2</version>
    15. </dependency>
    16. <dependency>
    17.     <groupId>com.fasterxml.jackson.module</groupId>
    18.     <artifactId>jackson-module-parameter-names</artifactId>
    19.     <version>2.13.2</version>
    20. </dependency>
    复制代码
  • 实现接口工程中的业务方法,使用 dubbo 中的注解暴露服务
    1. // @Component 可不用加此注解创建对象!加@DubboService后,该注解可自行创建该类对象。
    2. //@DubboService(interfaceClass = StudentService.class, version = "1.0", timeout = 5000)//暴露服务
    3. @DubboService(version = "1.0", timeout = 5000) // 暴露服务(interfaceClass属性可不加)
    4. public class StudentServiceImpl implements StudentService {
    5.     @Override
    6.     public Student queryStudent(Integer id) {
    7.         Student student = new Student();
    8.         if (1001 == id) {
    9.             student.setId(1001);
    10.             student.setName("1001-luis");
    11.             student.setAge(22);
    12.         } else {
    13.             student.setId(1002);
    14.             student.setName("1002-jack");
    15.             student.setAge(24);
    16.         }
    17.         return student;
    18.     }
    19. }
    复制代码
  • 配置 application.properties/yml 文件
    1. #配置服务名称
    2. spring.application.name=studentservice-provider
    3. #配置扫描的包,扫描@DubboService
    4. dubbo.scan.base-packages=com.luis.service
    5. #配置dubbo协议(使用zookeeper注册中心就不用配置)
    6. #dubbo.protocol.name=dubbo
    7. #dubbo.protocol.port=20881
    8. #配置zookeeper注册中心
    9. dubbo.registry.address=zookeeper://localhost:2181
    复制代码
  • 在主启动类上添加注解启用dubbo
    1. @SpringBootApplication
    2. @EnableDubbo // 启用dubbo,该注解包含@EnableDubboConfig和@DubboComponentScan
    3. public class SpringbootServiceProviderApplication {
    4.     public static void main(String[] args) {
    5.         SpringApplication.run(SpringbootServiceProviderApplication.class, args);
    6.     }
    7. }
    复制代码
3.创建服务消费者工程


  • 创建 SpringBoot 项目,添加 Spring Web 依赖,项目命令为 springboot-consumer(服务消费者工程)
  • 在其 pom 文件中加入公共工程依赖、dubbo 起步依赖和 Zookeeper 依赖,整理 pom,刷新。
    其需要的依赖和服务消费者工程所需相同!
    1. <dependency>
    2.     <groupId>com.luis</groupId>
    3.     <artifactId>interface-api</artifactId>
    4.     <version>1.0.0</version>
    5. </dependency>
    6. <dependency>
    7.     <groupId>org.apache.dubbo</groupId>
    8.     <artifactId>dubbo-spring-boot-starter</artifactId>
    9.     <version>2.7.8</version>
    10. </dependency>
    11. <dependency>
    12.     <groupId>org.apache.dubbo</groupId>
    13.     <artifactId>dubbo-dependencies-zookeeper</artifactId>
    14.     <version>2.7.8</version>
    15.     <type>pom</type>
    16.     <exclusions>
    17.         
    18.         <exclusion>
    19.             <artifactId>slf4j-log4j12</artifactId>
    20.             <groupId>org.slf4j</groupId>
    21.         </exclusion>
    22.     </exclusions>
    23. </dependency>
    复制代码
  • 创建控制器类,写请求处理方法,进行远程接口调用
    1. @RestController
    2. public class DubboController {
    3.     // 引用远程服务,将创建好的代理对象,注入给studentService
    4.     //@DubboReference(interfaceClass = StudentService.class, version = "1.0")
    5.     @DubboReference(version = "1.0") // 如果不指定interfaceClass,则默认采用引用类型的class
    6.     private StudentService studentService;
    7.     @GetMapping("/query")
    8.     public String queryStudent() {
    9.         // 调用远程接口,获取对象
    10.         Student student = studentService.queryStudent(1001);
    11.         return "调用远程接口获取的对象:" + student;
    12.     }
    13. }
    复制代码
  • 在主启动类上添加启用dubbo的注解
    1. @SpringBootApplication
    2. @EnableDubbo // 启用Dubbo
    3. public class SpringbootConsumerApplication {
    4.     public static void main(String[] args) {
    5.         SpringApplication.run(SpringbootConsumerApplication.class, args);
    6.     }
    7. }
    复制代码
  • 配置 application.properties/yml
    1. #指定服务名称
    2. spring.application.name=consumer-application
    3. #指定注册中心
    4. dubbo.registry.address=zookeeper://localhost:2181
    复制代码
4.启动 zookeeper 和服务


  • 启动 zookeeper 注册中心(双击 zookeeper/bin 目录下的 zkServer.cmd)
  • 运行服务提供者模块的主启动类
  • 运行服务消费者模块的主启动类
  • 根据服务消费者提供的访问接口进行服务访问测试
    1. http://localhost:8080/query
    复制代码
SpringBoot 项目打包

打包为 war 文件

示例:

  • 创建 SpringBoot 项目,选择 Spring Web 依赖,整理项目目录
  • 此处直接列举整个 pom,依据注释的内容进行添加,然后刷新 pom
    1. <?xml version="1.0" encoding="UTF-8"?>
    2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    3.          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    4.     <modelVersion>4.0.0</modelVersion>
    5.     <parent>
    6.         <groupId>org.springframework.boot</groupId>
    7.         <artifactId>spring-boot-starter-parent</artifactId>
    8.         <version>2.6.6</version>
    9.         <relativePath/>
    10.     </parent>
    11.     <groupId>com.luis</groupId>
    12.     <artifactId>springboot-war</artifactId>
    13.     <version>0.0.1-SNAPSHOT</version>
    14.    
    15.     <packaging>war</packaging>
    16.     <properties>
    17.         <java.version>1.8</java.version>
    18.     </properties>
    19.     <dependencies>
    20.         
    21.         <dependency>
    22.             <groupId>org.apache.tomcat.embed</groupId>
    23.             <artifactId>tomcat-embed-jasper</artifactId>
    24.         </dependency>
    25.         
    26.         <dependency>
    27.             <groupId>org.springframework.boot</groupId>
    28.             <artifactId>spring-boot-starter-web</artifactId>
    29.         </dependency>
    30.         <dependency>
    31.             <groupId>org.springframework.boot</groupId>
    32.             <artifactId>spring-boot-starter-test</artifactId>
    33.             <scope>test</scope>
    34.         </dependency>
    35.     </dependencies>
    36.     <build>
    37.         
    38.         <finalName>myboot</finalName>
    39.         
    40.         
    41.         <resources>
    42.             
    43.             <resource>
    44.                 <directory>src/main/webapp</directory>
    45.                 <targetPath>META-INF/resources</targetPath>
    46.                 <includes>
    47.                     <include>**/*.*</include>
    48.                 </includes>
    49.             </resource>
    50.             
    51.             <resource>
    52.                 <directory>src/main/java</directory>
    53.                 <includes>
    54.                     <include>**/*.*</include>
    55.                 </includes>
    56.             </resource>
    57.             
    58.             <resource>
    59.                 <directory>src/main/resources</directory>
    60.                 <includes>
    61.                     <include>**/*.*</include>
    62.                 </includes>
    63.             </resource>
    64.         </resources>
    65.         <plugins>
    66.             <plugin>
    67.                 <groupId>org.springframework.boot</groupId>
    68.                 <artifactId>spring-boot-maven-plugin</artifactId>
    69.             </plugin>
    70.         </plugins>
    71.     </build>
    72. </project>
    复制代码
  • 在 main 目录下,与 java 和 resources 目录平级,创建名为 webapp 的目录;在项目工程结构中指定该目录为 web 资源目录
  • 在 webapp 目录下创建 index.jsp 页面,用来显示 controller 中的数据
    1. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    2. <html>
    3. <head>
    4.     <title>index.jsp</title>
    5. </head>
    6. <body>
    7.     index.jsp,显示controller中的数据:${data}
    8. </body>
    9. </html>
    复制代码
  • 创建 controller 控制器类,处理请求
    1. @Controller
    2. public class JspController {
    3.     @RequestMapping("/main")
    4.     public String main(Model model) {
    5.         model.addAttribute("data", "SpringBoot打包为war文件");
    6.         return "index";
    7.     }
    8. }
    复制代码
  • 配置 application.properties/yml
    1. server.port=9001
    2. server.servlet.context-path=/myjsp
    3. #指定视图解析器
    4. spring.mvc.view.prefix=/
    5. spring.mvc.view.suffix=.jsp
    复制代码
  • 让主启动类继承 SpringBootServletInitializer并重写 configure 方法,修改返回内容。
    1. /**
    2. * 让主启动类继承 SpringBootServletInitializer 并重写重写 configure 方法才可以使用外部 Tomcat!
    3. * SpringBootServletInitializer 就是原有 web.xml 的替代。
    4. */
    5. @SpringBootApplication
    6. public class SpringbootWarApplication extends SpringBootServletInitializer {
    7.     public static void main(String[] args) {
    8.         SpringApplication.run(SpringbootWarApplication.class, args);
    9.     }
    10.     // 重写此configure方法,修改返回内容!
    11.     @Override
    12.     protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
    13.         return builder.sources(SpringbootWarApplication.class);
    14.     }
    15. }
    复制代码
  • 运行主启动类,浏览器输入访问地址,测试
    1. http://localhost:9001/myjsp/main
    复制代码
  • 测试正常后,使用 maven 的 lifecycle 中 package 打包命令进行打包(右侧 maven 窗口中);【建议先clean再package】
    在 target 目录下即可看到打包完成的 war 包。
  • 将打包好的 war 包放到 Tomcat 的 webapps 目录下,启动 Tomcat;
    若是本地 Tomcat,则通过http://localhost:8080/myboot/main可访问该项目。
重点小结:

  • 指定打包类型为 war
  • 指定打包后名称
  • 添加资源插件
  • 主启动类继承 SpringBootServletInitializer并重写 configure 方法,修改返回内容。
  • 使用 package 命令打包
打包为 jar 文件

示例:

  • 创建 SpringBoot 项目,选择 Spring Web 依赖,整理项目目录
  • 此处直接列举整个 pom,依据注释的内容进行添加,然后刷新 pom
    1. <?xml version="1.0" encoding="UTF-8"?>
    2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    3.          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    4.     <modelVersion>4.0.0</modelVersion>
    5.     <parent>
    6.         <groupId>org.springframework.boot</groupId>
    7.         <artifactId>spring-boot-starter-parent</artifactId>
    8.         <version>2.6.6</version>
    9.         <relativePath/>
    10.     </parent>
    11.     <groupId>com.luis</groupId>
    12.     <artifactId>springboot-jar</artifactId>
    13.     <version>0.0.1-SNAPSHOT</version>
    14.     <properties>
    15.         <java.version>1.8</java.version>
    16.     </properties>
    17.     <dependencies>
    18.         
    19.         <dependency>
    20.             <groupId>org.apache.tomcat.embed</groupId>
    21.             <artifactId>tomcat-embed-jasper</artifactId>
    22.         </dependency>
    23.         
    24.         <dependency>
    25.             <groupId>org.springframework.boot</groupId>
    26.             <artifactId>spring-boot-starter-web</artifactId>
    27.         </dependency>
    28.         <dependency>
    29.             <groupId>org.springframework.boot</groupId>
    30.             <artifactId>spring-boot-starter-test</artifactId>
    31.             <scope>test</scope>
    32.         </dependency>
    33.     </dependencies>
    34.     <build>
    35.         
    36.         <finalName>myboot</finalName>
    37.         
    38.         <resources>
    39.             
    40.             <resource>
    41.                 <directory>src/main/webapp</directory>
    42.                 <targetPath>META-INF/resources</targetPath>
    43.                 <includes>
    44.                     <include>**/*.*</include>
    45.                 </includes>
    46.             </resource>
    47.             
    48.             <resource>
    49.                 <directory>src/main/java</directory>
    50.                 <includes>
    51.                     <include>**/*.xml</include>
    52.                 </includes>
    53.             </resource>
    54.             
    55.             <resource>
    56.                 <directory>src/main/resources</directory>
    57.                 <includes>
    58.                     <include>**/*.*</include>
    59.                 </includes>
    60.             </resource>
    61.         </resources>
    62.         <plugins>
    63.             <plugin>
    64.                 <groupId>org.springframework.boot</groupId>
    65.                 <artifactId>spring-boot-maven-plugin</artifactId>
    66.                
    67.                 <version>1.4.2.RELEASE</version>
    68.             </plugin>
    69.         </plugins>
    70.     </build>
    71. </project>
    复制代码
  • 在 main 目录下,与 java 和 resources 目录平级,创建名为 webapp 的目录;在项目工程结构中指定该目录为 web 资源目录
  • 在 webapp 目录下创建 main.jsp 页面,用来显示 controller 中的数据
    1. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    2. <html>
    3. <head>
    4.     <title>Title</title>
    5. </head>
    6. <body>
    7.   main.jsp,显示数据:${data}
    8. </body>
    9. </html>
    复制代码
  • 创建控制器类,处理请求
    1. @Controller
    2. public class HelloController {
    3.     @RequestMapping("/hello")
    4.     public ModelAndView hello() {
    5.         ModelAndView mv = new ModelAndView();
    6.         mv.addObject("data", "SpringBoot打包为jar文件");
    7.         mv.setViewName("main");
    8.         return mv;
    9.     }
    10. }
    复制代码
  • 配置 application.properties/yml
    1. server.port=9002
    2. server.servlet.context-path=/myboot
    3. #视图解析器
    4. spring.mvc.view.prefix=/
    5. spring.mvc.view.suffix=.jsp
    复制代码
  • 运行主启动类,浏览器输入地址访问测试
    1. http://localhost:9002/myboot/hello
    复制代码
  • 测试正常后,使用 maven 的 lifecycle 中 package 打包命令进行打包(右侧 maven 窗口中);【建议先clean再package】
    在 target 目录下即可看到打包完成的 jar 包。
  • 在 jar 包所在目录,开启 cmd 窗口,输入 java -jar myboot.jar,回车,即可独立运行项目;
    (可以将java -jar myboot.jar这段命令写进一个文件,改后缀为 .bat,放在 jar 包同级下,双击即可运行项目)
    后台信息打印可看到端口和项目访问上下文路径;
    此时使用的是内嵌的 tomcat,输入http://localhost:9002/myboot/hello即可访问。
重点小结:

  • 指定打包名称
  • 添加资源插件
  • 指定 maven-plugin 插件版本
  • 使用 package 命令打包
Thymeleaf 模板引擎

Thymeleaf 介绍


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


  • 添加了 Thymeleaf 依赖后,在创建的 html 标签中使用其相关语法,若想使用 IDEA 的语法提示,还需进行以下设置:
    在默认创建的 html 的 中补充xmlns:th="http://www.thymeleaf.org",如下:
    1. [/code]
    2. [/list][size=4]使用示例[/size]
    3. [list=1]
    4. [*]创建 SpringBoot 项目,选择 Spring Web 和 Thymeleaf 依赖,整理 pom,并刷新
    5. [*]写控制器类,处理请求,转发页面到指定的 Thymeleaf 页面,显示数据
    6. [code]@Controller
    7. public class MyController {
    8.     @GetMapping("/hello")
    9.     public String helloThymeleaf(HttpServletRequest request, Model model) {
    10.         // 将数据放到request作用域
    11.         request.setAttribute("data1", "欢迎使用Thymeleaf模板引擎");
    12.         // 将数据放到request作用域
    13.         model.addAttribute("data2", "我是后台的数据");
    14.         // 指定转发的逻辑视图(使用Thymeleaf模板引擎,其通常使用的html)
    15.         // 模板引擎默认配置了resources/tmeplates下的以.html结尾文件的视图解析
    16.         return "hello";
    17.     }
    18. }
    复制代码
  • 在 resources/templates 下,创建 hello.html 页面显示数据(可在 html 标签中使用 Thymeleaf)
    1. <!DOCTYPE html>
    2. <html lang="en" xmlns:th="http://www.thymeleaf.org">
    3. <head>
    4.     <meta charset="UTF-8">
    5.     <title>hello.html</title>
    6. </head>
    7. <body>
    8.     <h3>Thymeleaf使用示例</h3>
    9.    
    10.     <p th:text="${data1}">想显示数据</p>
    11.     <p th:text="${data2}">静态展示数据</p>
    12. </body>
    13. </html>
    复制代码
  • 配置 application.properties/yml
    1. #关闭模板缓存,开发阶段配置,让修改立即生效(项目上线后需修改为false,效率更高)
    2. spring.thymeleaf.cache=false
    3. # 去掉html5的语法验证(thymeleaf对html的标签约束非常严格,所有的标签必须有开有闭,比如
    4. </br>或者<br/>是可以的,但是
    5. 会报错,
    6. # 配置spring.thymeleaf.mode=LEGACYHTML5 目的就是为了解决这个问题,可以使页面松校验。)
    7. spring.thymeleaf.mode=LEGACYHTML5
    8. #以下是一些可能用到的配置,需要改变时配置即可,一般不需要配置,使用默认即可
    9. #-------------------------------------------------
    10. #编码格式(默认是UTF-8)
    11. spring.thymeleaf.encoding=UTF-8
    12. #模板的类型(默认是HTML)
    13. spring.thymeleaf.mode=HTML
    14. #模板的前缀(默认是classpath:/templates/,其下html文件不用配置视图解析器,直接可用逻辑名称)
    15. spring.thymeleaf.prefix=classpath:/templates/
    16. #模板的后缀(默认是.html)
    17. spring.thymeleaf.suffix=.html
    18. #-------------------------------------------------
    复制代码
  • 运行主启动类,浏览器输入地址访问测试;
    然后不通过地址,直接在 idea 中点击右上角浏览器标识,打开 hello.html,查看效果
    1. http://localhost:8080/hello
    复制代码
    结果:后台没有数据传过来时,显示的是页面原有数据;后台有数据传过来,则覆盖原有数据进行显示!
    使用 Thymeleaf 可实现前后端同时有效开发,互不影响;前端可用自己的示例数据,后端只需进行数据替换!
表达式

1.标准变量表达式


  • 语法:${key}
  • 作用:从 request 作用域中获取 key 对应的文本数据;
    可使用request.setAttribute()或model.addAttribute()向 request 中存数据
  • 使用:在页面的 html 标签中,使用th:text="${key}"表达式
  • 示例:
    1. <!DOCTYPE html>
    2. <html lang="en" xmlns:th="http://www.thymeleaf.org">
    3. <head>
    4.     <meta charset="UTF-8">
    5.     <title>expression1</title>
    6. </head>
    7. <body>
    8.     <p3>标准变量表达式:${key}</p3>
    9.    
    10.         <p>获取相关数据:</p>
    11.         <p th:text="${msg}">msg</p>
    12.         <p th:text="${myuser.id}">id</p>
    13.         <p th:text="${myuser.name}">name</p>
    14.         <p th:text="${myuser.sex}">sex</p>
    15.         <p th:text="${myuser.age}">age</p>
    16.    
    17. </body>
    18. </html>
    复制代码
2.选择/星号变量表达式


  • 语法: *{key}
  • 作用:获取这个 key 对应的数据;*{key}需要和th:object这个属性一起使用,简化对象属性值的获取。
  • 示例:
    1. <!DOCTYPE html>
    2. <html lang="en" xmlns:th="http://www.thymeleaf.org">
    3. <head>
    4.     <meta charset="UTF-8">
    5.     <title>expression2</title>
    6. </head>
    7. <body>
    8.     <p3>选择变量表达式:*{key}</p3>
    9.     <p>获取对象相关数据:</p>
    10.    
    11.         <p th:text="*{id}">id</p>
    12.         <p th:text="*{name}">name</p>
    13.         <p th:text="*{sex}">sex</p>
    14.         <p th:text="*{age}">age</p>
    15.    
    16.     <p>使用*{}完整表示对象的属性值,此用法其实和${key}作用相同,了解即可</p>
    17.     <p th:text="*{myuser.name}">name</p>
    18. </body>
    19. </html>
    复制代码
3.链接表达式


  • 语法:@{url}
  • 作用:表示链接,可使用在如下等情境中
    1.    
    2. </head>
    3. <body>
    4.     <p3>使用模板属性可获取动态变量</p3>
    5.    
    6.     <form th:action="@{/login}" th:method="${methodAttr}">
    7.         <input th:type="text" th:name="${paramname}" th:value="${paramvalue}" />
    8.         <input type="button" value="按钮" id="btn" th:onclick="btnClick()" />
    9.     </form>
    10.     <p th:>获取动态变量,改变字体颜色</p>
    11.     <p th:>此处经过模板处理,若仍手动设置,需要使用字符串</p>
    12.     <p >原版的改变字体颜色</p>
    13. </body>
    14. </html>
    复制代码
th:each


  • each 循环,可以循环 List 集合,Array 数组,Map 集合
  • 其实整体循环方式差不多,只不过数据存储方式不一样,存取方式有一些差异。
th:each循环List/Array

each 循环集合 List 和循环数组 Array 语法相同!
语法:在一个 html 标签中,如下列方式使用 th:each(以下以 div 为例,实际多循环表格标签)
  1.     <p th:text="${集合循环成员}"></p>
  2. 集合循环成员,循环状态变量:两个名称都是自定义的。
  3. “循环状态变量”这个名称可不定义,默认名称是"集合循环成员Stat"
  4. 如果不定义“循环状态变量”,则直接可这样写:(但要使用其时,直接使用"集合循环成员Stat"这个默认的名称即可)
  5.     <p th:text="${集合循环成员}"></p>
复制代码
具体语法说明:
  1. th:each="user,iterStat:${userlist}"中的${userList}是后台传过来的集合
  2. ◼  user
  3. 定义变量,去接收遍历${userList}集合中的一个数据
  4. ◼  iterStat
  5. ${userList} 循环体的信息
  6. ◼  其中 user 及 iterStat 自己可以随便取名
  7. ◼  interStat 是循环体的信息,通过该变量可以获取如下信息
  8. index: 当前迭代对象的 index(从0开始计算)
  9. count: 当前迭代对象的个数(从1开始计算)这两个用的较多
  10. size: 被迭代对象的大小
  11. current: 当前迭代变量
  12. even/odd: 布尔值,当前循环是否是偶数/奇数(从0开始计算)
  13. first: 布尔值,当前循环是否是第一个
  14. last: 布尔值,当前循环是否是最后一个
  15. 注意:循环体信息 interStat 也可以不定义,则默认采用迭代变量加上 Stat 后缀,即 userStat
复制代码
示例:
  1. <!DOCTYPE html>
  2. <html lang="en" xmlns:th="http://www.thymeleaf.org">
  3. <head>
  4.     <meta charset="UTF-8">
  5.     <title>eachList.html</title>
  6. </head>
  7. <body>
  8.     <p3>each循环List</p3>
  9.     <table border="1">
  10.         <thead>
  11.             <tr>
  12.                 <th>id</th>
  13.                 <th>name</th>
  14.                 <th>sex</th>
  15.                 <th>age</th>
  16.                 <th>userStat</th>
  17.             </tr>
  18.         </thead>
  19.         <tbody>
  20.             <tr th:each="user,userStat:${myusers}">
  21.                 <td th:text="${user.id}"></td>
  22.                 <td th:text="${user.name}"></td>
  23.                 <td th:text="${user.sex}"></td>
  24.                 <td th:text="${user.age}"></td>
  25.                 <td th:text="${userStat}"></td>
  26.             </tr>
  27.         </tbody>
  28.     </table>
  29.     <br/>
  30.     <table border="1">
  31.         <thead>
  32.         <tr>
  33.             <th>id</th>
  34.             <th>name</th>
  35.             <th>sex</th>
  36.             <th>age</th>
  37.         </tr>
  38.         </thead>
  39.         <tbody>
  40.         
  41.         <tr th:each="user:${myusers}">
  42.             <td th:text="${user.id}"></td>
  43.             <td th:text="${user.name}"></td>
  44.             <td th:text="${user.sex}"></td>
  45.             <td th:text="${user.age}"></td>
  46.         </tr>
  47.         </tbody>
  48.     </table>
  49. </body>
  50. </html>
复制代码
th:each循环Map

语法:在一个 html 标签中,如下列方式使用 th:each(以下以 div 为例,实际多循环表格标签)
  1.     <p th:text="${集合循环成员.key}" ></p>
  2.     <p th:text="${集合循环成员.value}"></p>
  3. 集合循环成员,循环的状态变量:两个名称都是自定义的。
  4. “循环的状态变量”这个名称可以不定义,默认是"集合循环成员Stat"
  5. key:map集合中的key
  6. value:map集合key对应的value值
复制代码
循环 List-Map 示例

示例循环一个稍复杂点的数据类型如:List
第一次循环,取出每一个 Map;
第二次循环,取出每一个 Map 中的 key 和 value。
  1.    
  2.         <p th:text="${map.key}"></p>
  3.         <p th:text="${map.value}"></p>        
  4.    
复制代码
th:if和th:unless

th:if:判断语句,当条件为 true,显示 html 标签体内容,反之不显示;没有 else 语句
示例:
  1. 0">条件为true才显示此内容
  2. <p th:if="${sex=='m'}">性别是男才显示</p>
  3. <p th:if="${isLogin}">isLogin为true才显示</p>
  4. <p th:if="${age>18}">年龄大于18才显示</p>
  5. <p th:if="${str}">当str为空串表示true,会显示</p>
  6. <p th:if="${str}">当str为null表示false,不会显示</p>
复制代码
th:unless:判断语句,当条件为 false,显示 html 标签体内容,反之不显示;没有 else 语句
示例:
  1. 条件为false才显示此内容
  2. 动态变量控制的示例此处省略,和if的使用相同,就是显示条件相反!
复制代码
th:swith和th:case

th:switch 和 Java 中的 switch 是一样的;
进行条件匹配,按上下顺序匹配,一旦匹配成功则结束;否则使用默认的;无论如何,最终只有一个匹配上!

  • 语法:
  1.     <p th:case="值1">
  2.         结果1
  3.     </p>
  4.     <p th:case="值2">
  5.         结果2
  6.     </p>
  7.     <p th:case="*">
  8.         默认结果
  9.     </p>
  10.     以上的case只有一个语句执行
  11.    
复制代码
示例:
  1.     <p th:case="m">男</p>
  2.     <p th:case="f">女</p>
  3.     <p th:case="*">性别未知</p>
复制代码
th:inline


  • 作用:不依赖于 html 标签,直接通过内联表达式[[${key}]]来获取动态数据
  • th:inline有三个取值类型 (text, javascript 和 none),通常使用 text 和 javascript 这两个
  • 语法:th:inline="text/javascript"
  • 内联表达式:[[${key}]]
内联 text


  • 作用:在 html 标签外,获取动态数据。
  • 语法:th:line="text",不指定则默认使用内联 text!
  • 特点:可显示的指定使用内联 text,不指定则默认使用内联 text!
  • 示例:
    1.     <p>性别:[[${sex}]],年龄[[${age}]]</p>
    2.     <p>性别:[[${sex}]],年龄[[${age}]]</p>
    复制代码
内联 javascript


  • 作用:可以在 js 中,获取模版中的数据
  • 语法:th:inline="javascript",必须指定!
  • 示例:
    1. <button onclick="fun()">单击按钮</button>
    复制代码
自面量


  • 指在模板文件的表达式中使用的一些数据,如文本、数字、boolean、null
  1.      <h3>文本字面量: 使用单引号括起来的字符串</h3>
  2.      <p th:text="'我是'+${name}+',我所在的城市是'+${city}">数据显示</p>
  3.      <h3>数字字面量</h3>
  4.      <p th:if="${20>5}"> 20大于 5</p>
  5.      <h3>boolean字面量</h3>
  6.      <p th:if="${isLogin == true}">用户已经登录系统</p>
  7.      <h3>null字面量</h3>
  8.      <p th:if="${myuser != null}">有myuser数据</p>
复制代码
字符串连接

在模板文件的表达式中连接字符串有两种语法:

  • 将字符串使用单引号括起来,使用加号连接其他的字符串或者表达式:
  1. <p th:text="'我是'+${name}+',我所在的城市是'+${city}">数据显示</p>
复制代码

  • 使用双竖线,将需要拼接的字符串和表达时候写在双竖线中即可:|字符串和表达式|
  1. <p th:text="|我是${name},我所在城市是${city}|">
  2.     显示数据
  3. </p>
复制代码
运算符

<ul>算术运算:+ , - , * , / , %
关系比较:> , < , >= , 年龄大于 10 </p>    显示运算结果
    myuser是null
    myuser是null
    myuser不是null
   
   
三元运算符:        表达式  ? true的结果 : false的结果三元运算符可以嵌套[/code]Thymeleaf 基本对象

常用的内置对象有以下几个:

  • #request:表示 HttpServletRequest 对象
  • #session:表示 HttpSession 对象
  • session:表示一个 Map 对象,是 #session的简单表示方式,用来便捷获取 session 中指定 key 的值。
    1.     <h3>使用运算符</h3>
    2.     <p th:text="${age > 10}">年龄大于 10 </p>
    3.     <p th:text="${20 + 30}">显示运算结果</p>
    4.     <p th:if="${myuser == null}">myuser是null</p>
    5.     <p th:if="${myuser eq null}">myuser是null</p>
    6.     <p th:if="${myuser ne null}">myuser不是null</p>
    7.     <p th:text="${isLogin == true ? '用户已经登录' : '用户需要登录'}"></p>
    8.     <p th:text="${isLogin == true ? (age > 10 ? '年龄大于10' : '年龄小于10') : '用户需要登录'}"></p>
    9. 三元运算符:
    10.         表达式  ? true的结果 : false的结果
    11. 三元运算符可以嵌套
    复制代码
使用示例:
  1. #session.getAttribute("loginname") 等同 session.loginname
复制代码
Thymeleaf 内置工具类对象

内置工具类:Thymeleaf 自己的一些类,提供对日期、数字、字符串、list集合等的一些处理方法。
下面是一些常用的内置工具类对象:

  • #dates:处理日器的工具类
  • #numbers:处理数字的工具类
  • #strings:处理字符串的工具类
  • #lists:处理 list 集合的工具类
使用示例:
  1.      <h3>内置对象 #request,#session,session 的使用</h3>
  2.      <p>获取作用域中的数据</p>
  3.      <p th:text="${#request.getAttribute('requestData')}"></p>
  4.      <p th:text="${#session.getAttribute('sessionData')}"></p>
  5.      <p th:text="${session.loginname}"></p>
  6.      <br/>
  7.      <br/>
  8.      <h3>使用内置对象的方法</h3>
  9.      getRequestURL=<br/>
  10.      getRequestURI=<br/>
  11.      getQueryString=<br/>
  12.      getContextPath=<br/>
  13.      getServerName=<br/>
  14.      getServerPort=<br/>
复制代码
自定义模板


  • 作用:内容复用,定义一次,在其他的模板文件中可多次使用。
1.自定义模板


  • 模板定义语法:th:fragment="模板自定义名称"
  • 示例:(在 head.html 中创建下列模板)
    1.     <h3>日期类对象 #dates</h3>
    2.     <p th:text="${#dates.format(mydate )}"></p>
    3.     <p th:text="${#dates.format(mydate,'yyyy-MM-dd')}"></p>
    4.     <p th:text="${#dates.format(mydate,'yyyy-MM-dd HH:mm:ss')}"></p>
    5.     <p th:text="${#dates.year(mydate)}"></p>
    6.     <p th:text="${#dates.month(mydate)}"></p>
    7.     <p th:text="${#dates.monthName(mydate)}"></p>
    8.     <p th:text="${#dates.createNow()}"></p>
    9.     <br/>
    10.     <h3>内置工具类 #numbers,操作数字的</h3>
    11.     <p th:text="${#numbers.formatCurrency(mynum)}"></p>
    12.     <p th:text="${#numbers.formatDecimal(mynum,5,2)}"></p>
    13.     <br/>
    14.     <h3>内置工具类 #strings, 操作字符串</h3>
    15.     <p th:text="${#strings.toUpperCase(mystr)}"></p>
    16.     <p th:text="${#strings.indexOf(mystr,'power')}"></p>
    17.     <p th:text="${#strings.substring(mystr,2,5)}"></p>
    18.     <p th:text="${#strings.substring(mystr,2)}"></p>
    19.     <p th:text="${#strings.concat(mystr,'---java开发的黄埔军校---')}"></p>
    20.     <p th:text="${#strings.length(mystr)}"></p>
    21.     <p th:text="${#strings.length('hello')}"></p>
    22.     <p th:unless="${#strings.isEmpty(mystr)}"> mystring 不是 空字符串  </p>
    23.     <br/>
    24.     <h3>内置工具类 #lists, 操作list集合</h3>
    25.     <p th:text="${#lists.size(mylist)}"></p>
    26.     <p th:if="${#lists.contains(mylist,'a')}">有成员a</p>
    27.     <p th:if="!${#lists.isEmpty(mylist)}"> list 集合有多个成员</p>
    28.     <br/>
    29.     <h3>处理null</h3>
    30.    
    31.     <p th:text="${zoo?.dog?.name}"></p>
    复制代码
2.使用自定义模板

有两种使用的语法格式:

  • ~{文件名称 :: 自定义的模板名}
  • 文件名称 :: 自定义的模板名
PS:文件名称指的自定义的模板所在的 html 文件名,不含后缀
对于模板,有两种常用的使用方式:包含模板(th:include),插入模板(th:insert)
a.插入模板


  • 解释:是在原有标签中,将自定义的模板添加进来,不会失去原有标签,但原有标签下的内容将失去。
  • 语法

    • 格式1:th:insert="~{文件名称 :: 自定义的模板名}"
    • 格式2:th:insert="文件名称 :: 自定义的模板名"

  • 示例:(在 test.html 中,将 head.html 中名为 top 的模板插入到指定标签中)
    使用格式1:
    1.     <p>百度地址</p>
    2.     <p>www.baidu.com</p>
    复制代码
    使用格式2:
    1.     <p>百度地址</p>
    2.     <p>www.baidu.com</p>
    复制代码
b.包含模板


  • 解释:用自定义的模板替换原有标签,原有标签将不存在
  • 语法

    • 格式1:th:include="~{文件名称 :: 自定义的模板名}"
    • 格式2:th:include="文件名称 :: 自定义的模板名"

  • 示例:(在 test.html 中,将 head.html 中名为 top 的模板包含(替换)到指定的标签)
    使用格式1:
    1.     此div标签下内容将会丢失,但div标签仍然存在!
    复制代码
    使用格式2:
    1.     此div标签下内容将会丢失,但div标签仍然存在!
    复制代码
3.整个 html 作为模板

如果要将整个 html 的内容作为模板插入(insert)或包含(include)到指定的标签中,可使用下列几种方式:
示例:将整个 head.html 作为模板,插入到指定标签处
a.插入整个 html 模板
  1.     整个div标签将被完全替换为自定义的模板!
复制代码
示例:将整个 head.html 作为模板,包含(替换)到指定标签处
b.包含整个 html 模板
  1. 方式一:
  2.     将整个 head.html 作为模板,插入到此标签处!
  3. 方式二:
  4.     将整个 head.html 作为模板,插入到此标签处!
复制代码
4.使用其他目录中的模板

说明:如果要使用的自定义模板或要使用的整个 html 模板与当前页面不在同一目录下,则在指定使用模板的文件名时需要使用相对路径即可!
例如:在 test.html 某标签中要将同级 common 目录下 left.html 作为整个模板来使用:
  1. 方式一:
  2.     将整个 head.html 作为模板,包含(替换)到此标签处!
  3. 方式二:
  4.     将整个 head.html 作为模板,包含(替换)到此标签处!
复制代码
以上是使用其他目录中的整个 html 作为模板示例;使用其他目录中指定 html 页面中的某个自定义模板用法和其相同。
注解总结

Spring + SpringMVC + SpringBoot
  1. 方式一:插入
  2. 方式二:插入
  3. 方式一:包含
  4. 方式二:包含
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

郭卫东

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表