Springboot 시작하기
Springboot
- Springboot의 가장 큰 특징은 자동 조립입니다.
JSR303 데이터 검증
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 对象是否符合正则表达式的规则
자동 조립 원리
-
SpringBoot 시작은 많은 수의 자동 구성 클래스를로드합니다.
-
필요한 기능이 기본적으로 SpringBoot에서 작성한 자동 구성 클래스에 있는지 살펴 보겠습니다.
-
이 자동 구성 클래스에서 구성되는 구성 요소를 살펴 보겠습니다 (사용하려는 구성 요소가 존재하는 한 수동으로 구성 할 필요가 없음).
-
컨테이너의 자동 구성 클래스에 구성 요소를 추가 할 때 특정 속성은 속성 클래스에서 가져옵니다. 구성 파일에서 이러한 속성의 값만 지정하면됩니다.
- xxxxAutoConfigurartion : 컨테이너에 구성 요소를 추가하기위한 자동 구성 클래스
- xxxxProperties : 패키지 구성 파일의 관련 속성은 구성 할 application.yml 파일과 일대일 대응됩니다.
- 밤나무 봄 꽃을 줘
@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 从而知道哪些自动配置类生效
간단한 웹 프로젝트
- 1. 홈페이지 구성
- 모든 페이지의 정적 자원은 thymeleaf가 인수해야합니다.
- 2. 페이지 국제화
- i18n 파일 이름을 변경하지 않도록 구성해야합니다.
- 프로젝트에서 버튼을 자동으로 전환해야하는 경우 구성 요소를 사용자 정의해야합니다.
LocaleResolver
- 스프링 컨테이너에 작성한 구성 요소를 구성해야합니다.
@bean
- 3. 로그인 + 인터셉터
- 4. 추가, 삭제, 수정 및 확인
- 직원 목록 표시
- 공용 페이지를 추출하여 commons 폴더에 배치하십시오.
- 추출물:
th:fragment="sidebar"
- 끼워 넣다:
th:replace="~{commons/commons::sidebar(active='main.html')}
- 삽입은 대체 또는 삽입을 사용할 수 있습니다.
- (active = 'main.html') 삽입 과정에서 매개 변수를 전달하는 것과 동일합니까? active = 'main.html'이렇게하면 레이블이 강조 표시 될 수 있습니다.
- 추출물:
- 목록 루프 표시
- 공용 페이지를 추출하여 commons 폴더에 배치하십시오.
- 직원 추가
- 버튼 제출
- 페이지 추가로 이동
- 직원을 성공적으로 추가했습니다.
- 홈페이지로 돌아 가기
- 직원 목록 표시
Springboot는 Mybatis를 통합합니다.
- MyBatis에 필요한 종속성 가져 오기
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.1</version>
</dependency>
- 데이터베이스 연결 정보 구성 및 mybatis 구성 통합
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
- 데이터베이스 연결 성공 여부 테스트
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());
}
}
- 엔터티 클래스 만들기
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 레이어 (매퍼 인터페이스)
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);
}
- 인터페이스 구현 클래스 (매퍼 매핑 파일)는 일반적으로 리소스 디렉토리에 있습니다.
<?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>
- 컨트롤러 클래스
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";
}
}
- 테스트
- 브라우저에서 요청
http:localhost/8080/queryUserList
- 브라우저에서 요청
요약하자면
- 단기적으로 프로젝트에 Springboot + mybatis를 사용할 계획이라면이 프레임 워크를 사용하는 방법을 마스터 할 수 있습니다 (실제로는 매우 간단합니다).
- 추천 비디오 스테이션 B : Mad God said
- 권장 방법은 1.5 배 더 빠르며 키를 발견하면 속도를 늦추고 소스 코드 설명을 건너 뛸 수 있습니다.
- 앞으로 자바 백엔드 개발에 참여할 예정이라면 소스 코드를보고, 공식 문서를보고, 직접 요약하고, 일부 포럼에 참여하는 것이 좋습니다.