Build Anything with Spring Boot : Spring Boot is the starting point forbuilding all Spring-based applications. Spring Boot is designed to get you up andrunning as quickly as possible, with minimal upfront configuration of Spring.
上面是引自官网的一段话,大概是说: Spring Boot 是所有基于 Spring 开发的项目的起点。Spring Boot 的设计是为了让你尽可能快的跑起来 Spring 应用程序并且尽可能减少你的配置文件。
- <parent>
- <groupId>org.springframework.bootgroupId>
- <artifactId>spring-boot-starter-parentartifactId>
- <version>2.3.4.RELEASEversion>
- parent>
- <dependencies>
- <dependency>
- <groupId>org.springframework.bootgroupId>
- <artifactId>spring-boot-starter-webartifactId>
- dependency>
- dependencies>
- <build>
- <plugins>
- <plugin>
- <groupId>org.springframework.bootgroupId>
- <artifactId>spring-boot-maven-pluginartifactId>
- plugin>
- plugins>
- build>
- /**
- * SpringBoot的启动类通常放在二级包中,比如:com.lagou.SpringBootDemo1Application
- * 因为SpringBoot项目在做包扫描,会扫描启动类所在的包及其子包下的所有内容。
- */
- //标识当前类为SpringBoot项目的启动类
- @SpringBootApplication
- public class SpringBootDemo1Application {
- public static void main(String[] args) {
- //样板代码
- SpringApplication.run(SpringBootDemo1Application.class,args);
- }
- }
- package com.lagou.controller;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RestController;
- @RestController
- @RequestMapping("/hello")
- public class HelloController {
- @RequestMapping("/boot")
- public String helloBoot(){
- return "Hello Spring Boot";
- }
- }


Spring Boot项目就创建好了。创建好的Spring Boot项目结构如图:

使用Spring Initializr方式构建的Spring Boot项目会默认生成项目启动类、存放前端静态资源和页
- @RestController // 该注解为组合注解,等同于Spring中@Controller+@ResponseBody注解
- public class DemoController {
- @RequestMapping("/demo")
- public String demo(){
- return "hello spring Boot";
- }
- }
页面输出的内容是“hello Spring Boot”,至此,构建Spring Boot项目就完成了
- <dependency>
- <groupId>org.springframework.bootgroupId>
- <artifactId>spring-boot-starter-testartifactId>
- <scope>testscope>
- dependency>
- package com.lagou;
- import com.lagou.controller.HelloController;
- import org.junit.jupiter.api.Test;
- import org.junit.runner.RunWith;
- import org.junit.runners.JUnit4;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.boot.test.context.SpringBootTest;
- import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
- import org.springframework.test.context.junit4.SpringRunner;
- /**
- * SpringJUnit4ClassRunner.class:Spring运行环境
- * JUnit4.class:JUnit运行环境
- * SpringRunner.class:Spring Boot运行环境
- */
- @RunWith(SpringRunner.class) //@RunWith:运行器
- @SpringBootTest //标记为当前类为SpringBoot测试类,加载项目的ApplicationContext上下文环境
- class Springbootdemo2ApplicationTests {
- /**
- * 需求:调用HelloController的hello方法
- */
- @Autowired
- private HelloController helloController;
- @Test
- void contextLoads() {
- String result = helloController.hello();
- System.out.println(result);
- }
- }
- <dependency>
- <groupId>org.springframework.bootgroupId>
- <artifactId>spring-boot-devtoolsartifactId>
- dependency>
可以看出,浏览器输出了“你好,Spring Boot”,说明项目热部署配置成功
- #修改tomcat的版本号
- server.port=8888
- #定义数据库的连接信息 JdbcTemplate
- spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
- spring.datasource.url=jdbc:mysql://localhost:3306/lagou
- spring.datasource.username=root
- spring.datasource.password=wu7787879
- public class Pet {
- private String type;
- private String name;
- }
- @Component
- @ConfigurationProperties(prefix = "person")
- public class Person {
- private int id; //id
- private String name; //名称
- private List hobby; //爱好
- private String[] family; //家庭成员
- private Map map;
- private Pet pet; //宠物
- }
- #自定义配置信息
- person.id=1
- person.name=王二麻子
- person.hobby=read,write
- person.family=father,mather
- person.map.key1=value1
- person.map.key2=value2
- person.pet.type=dog
- person.pet.name=哈士奇
- @RunWith(SpringRunner.class) // 测试启动器,并加载Spring Boot测试注解
- @SpringBootTest // 标记为Spring Boot单元测试类,并加载项目的ApplicationContext上下文环
- 境
- class SpringbootDemoApplicationTests {
- // 配置测试
- @Autowired
- private Person person;
- @Test
- void configurationTest() {
- System.out.println(person);
- }
- }
设置Tomcat及Http编码
- #解决中文乱码
- server.tomcat.uri-encoding=UTF-8
- spring.http.encoding.force=true
- spring.http.encoding.charset=UTF-8
- spring.http.encoding.enabled=true
- server:
- port: 8080
- servlet:
- context-path: /hello
- person:
- hobby:
- - play
- - read
- - sleep
- person:
- hobby:
- play,
- read,
- sleep
- person:
- hobby: [play,read,sleep]
- person:
- map:
- k1: v1
- k2: v2
- person:
- map: {k1: v1,k2: v2}
- #对实体类对象Person进行属性配置
- person:
- id: 1
- name: 王二麻子
- family:
- - 妻
- - 妾
- hobby:
- - play
- - read
- - sleep
- map:
- k1: value1
- k2: value2
- pet:
- type: 狗
- name: 哈士奇
- <includes>
- <include>**/application*.ymlinclude>
- <include>**/application*.yamlinclude>
- <include>**/application*.propertiesinclude>
- includes>
- @Component
- //将配置文件中所有以person开头的配置信息注入当前类中
- //前提1:必须保证配置文件中person.xx与当前Person类的属性名一致
- //前提2:必须保证当前Person中的属性都具有set方法
- @ConfigurationProperties(prefix = "person")
- public class Person {
- private int id; //id
- private String name; //名称
- private List hobby; //爱好
- private String[] family; //家庭成员
- private Map map;
- private Pet pet; //宠物
- }
- @Component
- public class Person {
- @Value("${person.id}")
- private int id;
- }
- @Component
- public class Student {
- @Value("${person.id}")
- private int id;
- @Value("${person.name}")
- private String name; //名称
- //省略toString
- }
- @Autowired
- private Student student;
- @Test
- public void studentTest() {
- System.out.println(student);
- }
- #对实体类对象MyProperties进行属性配置
- test.id=110
- test.name=test
- @Component // 自定义配置类
- @PropertySource("classpath:test.properties") // 指定自定义配置文件位置和名称
- @ConfigurationProperties(prefix = "test") // 指定配置文件注入属性前缀
- public class MyProperties {
- private int id;
- private String name;
- // 省略属性getXX()和setXX()方法
- // 省略toString()方法
- }
- @Autowired
- private MyProperties myProperties;
- @Test
- public void myPropertiesTest() {
- System.out.println(myProperties);
- }
- public class MyService {
- }
- @Configuration // 定义该类是一个配置类````
- public class MyConfig {
- @Bean // 将返回值对象作为组件添加到Spring容器中,该组件id默认为方法名
- public MyService myService(){
- return new MyService();
- }
- }
- @Autowired
- private ApplicationContext applicationContext;
- @Test
- public void iocTest() {
- System.out.println(applicationContext.containsBean("myService"));
- }
- <parent>
- <groupId>org.springframework.bootgroupId>
- <artifactId>spring-boot-starter-parent<11./artifactId>
- <version>2.2.2.RELEASEversion>
- <relativePath/>
- parent>

- <parent>
- <groupId>org.springframework.bootgroupId>
- <artifactId>spring-boot-dependenciesartifactId>
- <version>2.2.2.RELEASEversion>
- <relativePath>../../spring-boot-dependenciesrelativePath>
- parent>
- <properties>
- <activemq.version>5.15.11activemq.version>
- ...
- <solr.version>8.2.0solr.version>
- <mysql.version>8.0.18mysql.version>
- <kafka.version>2.3.1kafka.version>
- <properties>
- <activemq.version>5.15.11activemq.version>
- ...
- <solr.version>8.2.0solr.version>
- <mysql.version>8.0.18mysql.version>
- <kafka.version>2.3.1kafka.version>

- <dependencies>
- <dependency>
- <groupId>org.springframework.bootgroupId>
- <artifactId>spring-boot-starterartifactId>
- <version>2.2.2.RELEASEversion>
- <scope>compilescope>
- dependency>
- <dependency>
- <groupId>org.springframework.bootgroupId>
- <artifactId>spring-boot-starter-jsonartifactId>
- <version>2.2.2.RELEASEversion>
- <scope>compilescope>
- dependency>
- <dependency>
- <groupId>org.springframework.bootgroupId>
- <artifactId>spring-boot-starter-tomcatartifactId>
- <version>2.2.2.RELEASEversion>
- <scope>compilescope>
- dependency>
- <dependency>
- <groupId>org.springframework.bootgroupId>
- <artifactId>spring-boot-starter-validationartifactId>
- <version>2.2.2.RELEASEversion>
- <scope>compilescope>
- <exclusions>
- <exclusion>
- <artifactId>tomcat-embed-elartifactId>
- <groupId>org.apache.tomcat.embedgroupId>
- exclusion>
- exclusions>
- dependency>
- <dependency>
- <groupId>org.springframeworkgroupId>
- <artifactId>spring-webartifactId>
- <version>5.2.2.RELEASEversion>
- <scope>compilescope>
- dependency>
- <dependency>
- <groupId>org.springframeworkgroupId>
- <artifactId>spring-webmvcartifactId>
- <version>5.2.2.RELEASEversion>
- <scope>compilescope>
- dependency>
- dependencies>
- @SpringBootApplication
- public class SpringbootDemoApplication {
- public static void main(String[] args) {
- SpringApplication.run(SpringbootDemoApplication.class, args);
- }
- }
- @Target({ElementType.TYPE}) //注解的适用范围,Type表示注解可以描述在类、接口、注解或枚举中
- @Retention(RetentionPolicy.RUNTIME) //表示注解的生命周期,Runtime运行时
- @Documented //表示注解可以记录在javadoc中
- @Inherited //表示可以被子类继承该注解
- @SpringBootConfiguration // 标明该类为配置类
- @EnableAutoConfiguration // 启动自动配置功能
- @ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes =
- TypeExcludeFilter.class),
- @Filter(type = FilterType.CUSTOM, classes =
- AutoConfigurationExcludeFilter.class) })
- public @interface SpringBootApplication {
- // 根据class来排除特定的类,使其不能加入spring容器,传入参数value类型是class类型。
- @AliasFor(annotation = EnableAutoConfiguration.class)
- Class>[] exclude() default {};
- // 根据classname 来排除特定的类,使其不能加入spring容器,传入参数value类型是class的全
- 类名字符串数组。
- @AliasFor(annotation = EnableAutoConfiguration.class)
- String[] excludeName() default {};
- // 指定扫描包,参数是包名的字符串数组。
- @AliasFor(annotation = ComponentScan.class, attribute = "basePackages")
- String[] scanBasePackages() default {};
- // 扫描特定的包,参数类似是Class类型数组。
- @AliasFor(annotation = ComponentScan.class, attribute =
- "basePackageClasses")
- Class>[] scanBasePackageClasses() default {};
- }
- @Target({ElementType.TYPE})
- @Retention(RetentionPolicy.RUNTIME)
- @Documented
- @Configuration // 配置类的作用等同于配置文件,配置类也是容器中的一个对象
- public @interface SpringBootConfiguration {
- }
- // 自动配置包
- @AutoConfigurationPackage
- // Spring的底层注解@Import,给容器中导入一个组件;
- // 导入的组件是AutoConfigurationPackages.Registrar.class
- @Import(AutoConfigurationImportSelector.class)
- // 告诉SpringBoot开启自动配置功能,这样自动配置才能生效。
- public @interface EnableAutoConfiguration {
- String ENABLED_OVERRIDE_PROPERTY = "spring.boot.enableautoconfiguration";
- // 返回不会被导入到 Spring 容器中的类
- Class>[] exclude() default {};
- // 返回不会被导入到 Spring 容器中的类名
- String[] excludeName() default {};
- }
- @Target({ElementType.TYPE})
- @Retention(RetentionPolicy.RUNTIME)
- @Documented
- @Inherited
- @Import({Registrar.class}) // 导入Registrar中注册的组件
- public @interface AutoConfigurationPackage {
- }
深入研究loadMetadata方法

AutoConfigurationImportSelector类 getAutoConfigurationEntry方法
- protected AutoConfigurationEntry
- getAutoConfigurationEntry(AutoConfigurationMetadata autoConfigurationMetadata,
- AnnotationMetadata annotationMetadata) {
- //判断EnabledAutoConfiguration注解有没有开启,默认开启
- if (!isEnabled(annotationMetadata)) {
- return EMPTY_ENTRY;
- }
- //获得注解的属性信息
- AnnotationAttributes attributes = getAttributes(annotationMetadata);
- //获取默认支持的自动配置类列表
- List
configurations = - getCandidateConfigurations(annotationMetadata, attributes);
- //去重
- configurations = removeDuplicates(configurations);
- //去除一些多余的配置类,根据EnabledAutoConfiguratio的exclusions属性进行排除
- Set
exclusions = getExclusions(annotationMetadata, attributes); - checkExcludedClasses(configurations, exclusions);
- configurations.removeAll(exclusions);
- //根据pom文件中加入的依赖文件筛选中最终符合当前项目运行环境对应的自动配置类
- configurations = filter(configurations, autoConfigurationMetadata);
- //触发自动配置导入监听事件
- fireAutoConfigurationImportEvents(configurations, exclusions);
- return new AutoConfigurationEntry(configurations, exclusions);
- }
继续点开loadFactory方法
- public static List
loadFactoryNames(Class> factoryClass, @Nullable - ClassLoader classLoader) {
- //获取出入的键
- String factoryClassName = factoryClass.getName();
- return
- (List)loadSpringFactories(classLoader).getOrDefault(factoryClassName,
- Collections.emptyList());
- }
- private static Map
> loadSpringFactories(@Nullable - ClassLoader classLoader) {
- MultiValueMap
result = - (MultiValueMap)cache.get(classLoader);
- if (result != null) {
- return result;
- } else {
- try {
- //如果类加载器不为null,则加载类路径下spring.factories文件,将其中设置的
- 配置类的全路径信息封装 为Enumeration类对象
- Enumeration
urls = classLoader != null ? - classLoader.getResources("META-INF/spring.factories") :
- ClassLoader.getSystemResources("META-INF/spring.factories");
- LinkedMultiValueMap result = new LinkedMultiValueMap();
- //循环Enumeration类对象,根据相应的节点信息生成Properties对象,通过传入的
- 键获取值,在将值切割为一个个小的字符串转化为Array,方法result集合中
- while(urls.hasMoreElements()) {
- URL url = (URL)urls.nextElement();
- UrlResource resource = new UrlResource(url);
- Properties properties =
- PropertiesLoaderUtils.loadProperties(resource);
- Iterator var6 = properties.entrySet().iterator();
- while(var6.hasNext()) {
- Entry, ?> entry = (Entry)var6.next();
- String factoryClassName =
- ((String)entry.getKey()).trim();
- String[] var9 =
- StringUtils.commaDelimitedListToStringArray((String)entry.getValue());
- int var10 = var9.length;
- for(int var11 = 0; var11 < var10; ++var11) {
- String factoryName = var9[var11];
- result.add(factoryClassName, factoryName.trim());
- }
- }
- }
- cache.put(classLoader, result);
- return result;
- public final class SpringFactoriesLoader {
- public static final String FACTORIES_RESOURCE_LOCATION = "METAINF/spring.factories";
- }

- |- @SpringBootConfiguration
- |- @Configuration //通过javaConfig的方式来添加组件到IOC容器中
- |- @EnableAutoConfiguration
- |- @AutoConfigurationPackage //自动配置包,与@ComponentScan扫描到的添加到IOC
- |- @Import(AutoConfigurationImportSelector.class) //到METAINF/spring.factories中定义的bean添加到IOC容器中
- |- @ComponentScan //包扫描
- # 创建数据库
- CREATE DATABASE springbootdata;
- # 选择使用数据库
- USE springbootdata;
- # 创建表t_article并插入相关数据
- DROP TABLE IF EXISTS t_article;
- CREATE TABLE t_article (
- id int(20) NOT NULL AUTO_INCREMENT COMMENT '文章id',
- title varchar(200) DEFAULT NULL COMMENT '文章标题',
- content longtext COMMENT '文章内容',
- PRIMARY KEY (id)
- ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
- INSERT INTO t_article VALUES ('1', 'Spring Boot基础入门', '从入门到精通讲解...');
- INSERT INTO t_article VALUES ('2', 'Spring Cloud基础入门', '从入门到精通讲
- 解...');
- # 创建表t_comment并插入相关数据
- DROP TABLE IF EXISTS t_comment;
- CREATE TABLE t_comment (
- id int(20) NOT NULL AUTO_INCREMENT COMMENT '评论id',
- content longtext COMMENT '评论内容',
- author varchar(200) DEFAULT NULL COMMENT '评论作者',
- a_id int(20) DEFAULT NULL COMMENT '关联的文章id',
- PRIMARY KEY (id)
- ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
- INSERT INTO t_comment VALUES ('1', '很全、很详细', 'lucy', '1');
- INSERT INTO t_comment VALUES ('2', '赞一个', 'tom', '1');
- INSERT INTO t_comment VALUES ('3', '很详细', 'eric', '1');
- INSERT INTO t_comment VALUES ('4', '很好,非常详细', '张三', '1');
- INSERT INTO t_comment VALUES ('5', '很不错', '李四', '2');
- public class Comment {
- private Integer id;
- private String content;
- private String author;
- private Integer aId;
- }
- public class Article {
- private Integer id;
- private String title;
- private String content;
- }
- # MySQL数据库连接配置
- spring:
- datasource:
- url: jdbc:mysql://localhost:3306/springbootdata?
- serverTimezone=UTC&characterEncoding=UTF-8
- username: root
- password: wu7787879
- public interface CommentMapper {
- @Select("SELECT * FROM t_comment WHERE id =#{id}")
- public Comment findById(Integer id);
- }
- @SpringBootApplication
- @MapperScan("com.lagou.mapper")
- public class Springboot02MybatisApplication {
- public static void main(String[] args) {
- SpringApplication.run(Springboot02MybatisApplication.class, args);
- }
- }
- @RunWith(SpringRunner.class)
- @SpringBootTest
- class SpringbootPersistenceApplicationTests {
- @Autowired
- private CommentMapper commentMapper;
- @Test
- void contextLoads() {
- Comment comment = commentMapper.findById(1);
- System.out.println(comment);
- }
- }
- #开启驼峰命名匹配映射
- mybatis:
- configuration:
- map-underscore-to-camel-case: true
- @Mapper
- public interface ArticleMapper {
- public Article selectArticle(Integer id);
- }
- "1.0" encoding="UTF-8" ?>
- mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
- "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
- <mapper namespace="com.lagou.mapper.ArticleMapper">
- <select id="selectArticle" resultType="Article">
- select * from Article
- select>
- mapper>
- mybatis:
- #配置MyBatis的xml配置文件路径
- mapper-locations: classpath:mapper/*.xml
- #配置XML映射文件中指定的实体类别名路径
- type-aliases-package: com.lagou.base.pojo
- @Autowired
- private ArticleMapper articleMapper;
- @Test
- void contextLoads2() {
- Article article = articleMapper.selectByPrimaryKey(1);
- System.out.println(article);
- }
- <dependency>
- <groupId>org.springframework.bootgroupId>
- <artifactId>spring-boot-starter-data-redisartifactId>
- dependency>
- #redis配置
- #Redis服务器地址
- spring.redis.host=127.0.0.1
- #Redis服务器连接端口
- spring.redis.port=6379
- #Redis数据库索引(默认为0)
- spring.redis.database=0
- #连接池最大连接数(使用负值表示没有限制)
- spring.redis.jedis.pool.max-active=50
- #连接池最大阻塞等待时间(使用负值表示没有限制)
- spring.redis.jedis.pool.max-wait=3000
- #连接池中的最大空闲连接
- spring.redis.jedis.pool.max-idle=20
- #连接池中的最小空闲连接
- spring.redis.jedis.pool.min-idle=2
- #连接超时时间(毫秒)
- spring.redis.timeout=5000
- package com.lagou.utils;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.data.redis.core.RedisTemplate;
- import org.springframework.stereotype.Component;
- import java.util.concurrent.TimeUnit;
- @Component
- public class RedisUtils {
- @Autowired
- private RedisTemplate redisTemplate;
- /**
- * 读取缓存
- *
- * @param key
- * @return
- */
- public Object get(final String key) {
- return redisTemplate.opsForValue().get(key);
- }
- /**
- * 写入缓存
- */
- public boolean set( String key, Object value) {
- boolean result = false;
- try {
- redisTemplate.opsForValue().set(key, value,1, TimeUnit.DAYS);
- result = true;
- } catch (Exception e) {
- e.printStackTrace();
- }
- return result;
- }
- /**
- * 更新缓存
- */
- public boolean getAndSet(final String key, String value) {
- boolean result = false;
- try {
- redisTemplate.opsForValue().getAndSet(key, value);
- result = true;
- } catch (Exception e) {
- e.printStackTrace();
- }
- return result;
- }
- /**
- * 删除缓存
- */
- public boolean delete(final String key) {
- boolean result = false;
- try {
- redisTemplate.delete(key);
- result = true;
- } catch (Exception e) {
- e.printStackTrace();
- }
- return result;
- }
- }
- @RunWith(SpringRunner.class)
- @SpringBootTest
- class Springboot02MybatisApplicationTests {
- @Autowired
- private RedisUtils redisUtils;
- @Autowired
- private CommentMapper commentMapper;
- @Test
- public void setRedisData() {
- redisUtils.set("article_1",articleMapper.selectByPrimaryKey(1));
- System.out.println("success");
- }
- @Test
- public void getRedisData() {
- Article article = (Article) redisUtils.get("article_1");
- System.out.println(article);
- }
- html>
- <html lang="en" xmlns:th="http://www.thymeleaf.org">
- <head>
- <meta charset="UTF-8">
- <link rel="stylesheet" type="text/css" media="all"
- href="../../css/gtvg.css" th:href="@{/css/gtvg.css}" />
- <title>Titletitle>
- head>
- <body>
- <p th:text="${hello}">欢迎进入Thymeleaf的学习p>
- body>
- html>

|
th
:标签
|
说明
|
|
th:insert
|
布局标签,替换内容到引入的文件
|
|
th:replace
|
页面片段包含(类似
JSP
中的
include
标签)
|
|
th:each
|
元素遍历(类似
JSP
中的
c:forEach
标签)
|
|
th:if
|
条件判断,如果为真
|
|
th:unless
|
条件判断,如果为假
|
|
th:switch
|
条件判断,进行选择性匹配
|
|
th:case
|
条件判断,进行选择性匹配
|
|
th:value
|
属性值修改,指定标签属性值
|
|
th:href
|
用于设定链接地址
|
|
th:src
|
用于设定链接地址
|
|
th:text
|
用于指定标签显示的文本内容
|
|
说明
|
表达式语法
|
|
变量表达式
|
${...}
|
|
选择变量表达式
|
*{...}
|
|
消息表达式
|
#{...}
|
|
链接
URL
表达式
|
@{...}
|
|
片段表达式
|
~{...}
|
<p th:text="${title}">这是标题p>
- # ctx:上下文对象
- # vars:上下文变量
- # locale:上下文区域设置
- # request:(仅限Web Context)HttpServletRequest对象
- # response:(仅限Web Context)HttpServletResponse对象
- # session:(仅限Web Context)HttpSession对象
- # servletContext:(仅限Web Context)ServletContext对象
The locale country is: <span th:text="${#locale.country}">USspan>.
- <div th:object="${book}">
- <p>titile: <span th:text="*{title}">标题span>.p>
- div>
- <a th:href="@{http://localhost:8080/order/details(orderId=${o.id})}">viewa>
- <a th:href="@{/order/details(orderId=${o.id},pid=${p.id})}">viewa>
<div th:insert="~{thymeleafDemo::title}">div>
- <dependency>
- <groupId>org.springframework.bootgroupId>
- <artifactId>spring-boot-starter-thymeleafartifactId>
- dependency>
- spring.thymeleaf.cache = true #启用模板缓存
- spring.thymeleaf.encoding = UTF_8 #模板编码
- spring.thymeleaf.mode = HTML5 #应用于模板的模板模式
- spring.thymeleaf.prefix = classpath:/templates/ #指定模板页面存放路径
- spring.thymeleaf.suffix = .html #指定模板页面名称的后缀
- # thymeleaf页面缓存设置(默认为true),开发中方便调试应设置为false,上线稳定后应保持默认
- true
- spring.thymeleaf.cache=false
- @Controller
- public class LoginController {
- /**
- * 获取并封装当前年份跳转到登录页login.html
- */
- @RequestMapping("/toLoginPage")
- public String toLoginPage(Model model){
- model.addAttribute("currentYear",
- Calendar.getInstance().get(Calendar.YEAR));
- return "login";
- }
- html>
- <html lang="en" xmlns:th="http://www.thymeleaf.org">
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1,shrinkto-fit=no">
- <title>用户登录界面title>
- <link th:href="@{/login/css/bootstrap.min.css}" rel="stylesheet">
- <link th:href="@{/login/css/signin.css}" rel="stylesheet">
- head>
- <body class="text-center">
- <form class="form-signin">
- <img class="mb-4" th:src="@{/login/img/login.jpg}" width="72" height="72">
- <h1 class="h3 mb-3 font-weight-normal">请登录h1>
- <input type="text" class="form-control"
- th:placeholder="用户名" required="" autofocus="">
- <input type="password" class="form-control"
- th:placeholder="密码" required="">
- <div class="checkbox mb-3">
- <label>
- <input type="checkbox" value="remember-me"> 记住我
- label>
- div>
- <button class="btn btn-lg btn-primary btn-block" type="submit" >登录button>
- <p class="mt-5 mb-3 text-muted">© <span
- th:text="${currentYear}">2019span>-<span
- th:text="${currentYear}+1">2020span>p>
- form>
- body>
- html>
- <dependency>
- <groupId>org.projectlombokgroupId>
- <artifactId>lombokartifactId>
- <version>1.18.12version>
- <scope>providedscope>
- dependency>
- <dependency>
- <groupId>com.alibabagroupId>
- <artifactId>druidartifactId>
- <version>1.1.3version>
- dependency>
- @Data
- public class User implements Serializable {
- private Integer id;
- private String username;
- private String password;
- private String birthday;
- private static final long serialVersionUID = 1L;
- }
- public interface UserMapper {
- int deleteByPrimaryKey(Integer id);
- int insert(User record);
- int insertSelective(User record);
- User selectByPrimaryKey(Integer id);
- int updateByPrimaryKeySelective(User record);
- int updateByPrimaryKey(User record);
- List
queryAll(); - }
- "1.0" encoding="UTF-8"?>
- mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
- "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
- <mapper namespace="com.example.base.mapper.UserMapper">
- <resultMap id="BaseResultMap" type="com.example.base.pojo.User">
- <id column="id" jdbcType="INTEGER" property="id" />
- <result column="username" jdbcType="VARCHAR" property="username" />
- <result column="password" jdbcType="VARCHAR" property="password" />
- <result column="birthday" jdbcType="VARCHAR" property="birthday" />
- resultMap>
- <sql id="Base_Column_List">
- id, username, password, birthday
- sql>
- <select id="selectByPrimaryKey" parameterType="java.lang.Integer"
- resultMap="BaseResultMap">
- select
- <include refid="Base_Column_List" />
- from user
- where id = #{id,jdbcType=INTEGER}
- select>
- <select id="queryAll" resultType="com.example.base.pojo.User">
- select <include refid="Base_Column_List" />
- from user
- select>
- .......
- mapper>
- package com.lagou.service.impl;
- import com.lagou.mapper.UserMapper;
- import com.lagou.pojo.User;
- import com.lagou.service.UserService;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Service;
- import java.util.List;
- @Service
- public class UserServiceImpl implements UserService {
- @Autowired
- private UserMapper userMapper;
- @Override
- public List
queryAll() { - return userMapper.queryAll();
- }
- @Override
- public User findById(Integer id) {
- return userMapper.selectByPrimaryKey(id);
- }
- @Override
- public void insert(User user) {
- //userMapper.insert(user); //将除id所有的列都拼SQL
- userMapper.insertSelective(user); //只是将不为空的列才拼SQL
- }
- @Override
- public void deleteById(Integer id) {
- userMapper.deleteByPrimaryKey(id);
- }
- @Override
- public void update(User user) {
- userMapper.updateByPrimaryKeySelective(user);
- }
- }
- package com.lagou.controller;
- import com.lagou.pojo.User;
- import com.lagou.service.UserService;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.web.bind.annotation.*;
- import org.yaml.snakeyaml.events.Event;
- import java.util.List;
- @RestController
- @RequestMapping("/user")
- public class UserController {
- @Autowired
- private UserService userService;
- /**
- * restful格式进行访问
- * 查询:GET
- * 新增: POST
- * 更新:PUT
- * 删除: DELETE
- */
- /**
- * 查询所有
- * @return
- */
- @GetMapping("/query")
- public List
queryAll(){ - return userService.queryAll();
- }
- /**
- * 通过ID查询
- */
- @GetMapping("/query/{id}")
- public User queryById(@PathVariable Integer id){
- return userService.findById(id);
- }
- /**
- * 删除
- * @param id
- * @return
- */
- @DeleteMapping("/delete/{id}")
- public String delete(@PathVariable Integer id){
- userService.deleteById(id);
- return "删除成功";
- }
- /**
- * 新增
- * @param user
- * @return
- */
- @PostMapping("/insert")
- public String insert(User user){
- userService.insert(user);
- return "新增成功";
- }
- /**
- * 修改
- * @param user
- * @return
- */
- @PutMapping("/update")
- public String update(User user){
- userService.update(user);
- return "修改成功";
- }
- }
- ##服务器配置
- server:
- port: 8090
- servlet:
- context-path: /
- ##数据源配置
- spring:
- datasource:
- name: druid
- type: com.alibaba.druid.pool.DruidDataSource
- url: jdbc:mysql://localhost:3306/springbootdata?characterEncoding=utf-
- 8&serverTimezone=UTC
- username: root
- password: wu7787879
- #整合mybatis
- mybatis:
- mapper-locations: classpath:mapper/*Mapper.xml #声明Mybatis映射文件所在的位置
- @SpringBootApplication
- //使用的Mybatis,扫描com.lagou.mapper
- @MapperScan("com.lagou.mapper")
- public class Springbootdemo5Application {
- public static void main(String[] args) {
- SpringApplication.run(Springbootdemo5Application.class, args);
- }
- }


- <build>
- <plugins>
- <plugin>
- <groupId>org.springframework.bootgroupId>
- <artifactId>spring-boot-maven-pluginartifactId>
- plugin>
- plugins>
- build>
java -jar 包名