Getting started with Springboot
Springboot
- The biggest feature of Springboot is automatic assembly
JSR303 data verification
1.举个栗子春暖花开
@Component //组件,方便springboot自动配置
@ConfigurationProperties(prefix = "person") //给实体类赋值
@Validated //数据验证
public class Person {
@Email(message="邮箱格式错误")
private String name; //name必须是邮箱格式
}
2.数据校验常见参数
@NotNull(message="名字不能为空")
private String userName;
@Max(value=120,message="年龄最大不能查过120")
private int age;
@Email(message="邮箱格式错误")
private String email;
空检查
@Null 验证对象是否为null
@NotNull 验证对象是否不为null, 无法查检长度为0的字符串
@NotBlank 检查约束字符串是不是Null还有被Trim的长度是否大于0,只对字符串,且会去掉前后空格.
@NotEmpty 检查约束元素是否为NULL或者是EMPTY.
Booelan检查
@AssertTrue 验证 Boolean 对象是否为 true
@AssertFalse 验证 Boolean 对象是否为 false
长度检查
@Size(min=, max=) 验证对象(Array,Collection,Map,String)长度是否在给定的范围之内
@Length(min=, max=) string is between min and max included.
日期检查
@Past 验证 Date 和 Calendar 对象是否在当前时间之前
@Future 验证 Date 和 Calendar 对象是否在当前时间之后
@Pattern 验证 String 对象是否符合正则表达式的规则
Principles of automatic assembly
-
SpringBoot startup will load a large number of automatic configuration classes
-
Let's see if the functions we need are in the automatic configuration classes written by SpringBoot by default
-
Let's look at which components are configured in this automatic configuration class (as long as the components we want to use exist in them, we don't need to configure them manually)
-
When adding components to the auto-configuration class in the container, certain properties are obtained from the properties class. We only need to specify the values of these properties in the configuration file
- xxxxAutoConfigurartion: Automatic configuration class to add components to the container
- xxxxProperties: The relevant properties in the package configuration file have a one-to-one correspondence with our application.yml file to configure
- Give a chestnut spring blossoms
@ConfigurationProperties(prefix = "server") public class ServerProperties { private Integer port; //... } 首先在autoconfigure文件下的META-INF里找到spring.factories文件 HttpEncodingAutoConfiguration-----------------ServerProperties-----------------server 所以我们才可以在application.yml文件中使用server.port 我们也可以通过在application.yml文件中写入debug=true 从而知道哪些自动配置类生效
A simple web project
- 1. Home page configuration
- The static resources of all pages need to be taken over by thymeleaf
- 2. Page internationalization
- We need to configure the i18n file name to not change
- If we need to automatically switch buttons in the project, we need to customize a component
LocaleResolver
- Remember to configure the components you wrote to the spring container
@bean
- 3. Login + interceptor
- 4. Add, delete, modify and check
- Employee list display
- Extract public pages and place them in the commons folder
- extract:
th:fragment="sidebar"
- insert:
th:replace="~{commons/commons::sidebar(active='main.html')}
- Insert can use replace or insert
- (active='main.html') is the equivalent of passing parameters during the insertion process? active='main.html' This may ensure that the label is highlighted
- extract:
- List loop display
- Extract public pages and place them in the commons folder
- Add employee
- Button submit
- Jump to add page
- Added employee successfully
- Back to homepage
- Employee list display
Springboot integrates Mybatis
- Import the dependencies required by MyBatis
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.1</version>
</dependency>
- Configure database connection information and integrate mybatis configuration
spring:
datasource:
username: root
password: 123qwe
#?serverTimezone=UTC解决时区的报错
url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
driver-class-name: com.mysql.cj.jdbc.Driver
#整合mybatis
mybatis:
type-aliases-package: com.kuang.pojo
mapper-locations: classpath:mybatis/mapper/*.xml
- Test whether the database connection is successful
package com.kuang;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import javax.sql.DataSource;
import java.sql.SQLException;
@SpringBootTest
class Springboot03ApplicationTests {
@Autowired
DataSource dataSource;
@Test
void contextLoads() throws SQLException {
System.out.println(dataSource);
System.out.println(dataSource.getConnection());
}
}
- Create entity class
package com.kuang.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Department {
private Integer id;
private String departmentName;
}
- DAO layer (Mapper interface)
package com.kuang.mapper;
import com.kuang.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
import java.util.List;
//这个注解表示了这是一个mybatis的mapper类
@Mapper
@Repository
public interface UserMapper {
List<User> queryUserList();
User queryUserById(int id);
int addUser(User user);
int deleteUser(int id);
}
- Interface implementation classes (Mapper mapping files) are generally placed in the resources directory
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.kuang.mapper.UserMapper">
<select id="queryUserList" resultType="User">
select * from user;
</select>
<select id="queryUserById" resultType="User">
select * from user where id=#{
id};
</select>
<insert id="addUser" parameterType="User">
insert into user(id,name,pwd) values(#{
id},#{
name},#{
pwd});
</insert>
<delete id="deleteUser" parameterType="int">
delete from user where id=#{
id};
</delete>
</mapper>
- controller class
package com.kuang.controller;
import com.kuang.mapper.UserMapper;
import com.kuang.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class UserController {
@Autowired
private UserMapper userMapper;
@GetMapping("/queryUserList")
public List<User> queryUserList(){
List<User> userList=userMapper.queryUserList();
return userList;
}
@GetMapping("/queryUserById/{id}")
public User queryUserById(@PathVariable("id") int id){
User user=userMapper.queryUserById(id);
return user;
}
@GetMapping("/addUser")
public String addUser(){
userMapper.addUser(new User(8,"阿毛","423562"));
return "add ok";
}
@GetMapping("/deleteUser")
private String deleteUser(){
userMapper.deleteUser(8);
return "delete ok";
}
}
- test
- Request in the browser
http:localhost/8080/queryUserList
- Request in the browser
to sum up
- If you plan to use Springboot+mybatis for your project in the short term, then you can master how to use this framework (it's actually very simple).
- Recommended video station B: Mad God said
- The recommended method is 1.5 times faster. If you encounter the key, you can slow down and you can skip the source code explanation.
- If you are going to be engaged in java back-end development in the future, it is recommended to look at the source code, see the official documents, do your own summary, and participate in some forums.