SpringBoot integrates thymeleaf’s simple CRUD
Recently, I found that I have forgotten a lot of things I learned before. Here I start to record some things I learned before every day. Today, I will start with the simplest CRUD.
First, look at the corresponding directory structure
Add the corresponding POM dependencies
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> < the groupId > mysql < / groupId > < artifactId > mysql connector - Java < / artifactId > < version > 5.1.47 < / version > < scope > runtime < / scope > </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <! --mybatis--> <dependency> <groupId>org.mybatis.spring.boot</groupId> < artifactId > mybatis - spring - the boot - starter < / artifactId > < version > 2.1.1 < / version > < / dependency > <! --druid--> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> </dependency>Copy the code
Create the corresponding entity class
Emp:
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class Emp {
private String id;
private String name;
private Double salary;
private Integer age;
private Date bir;
}
Copy the code
User:
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class User {
private String id;
private String username;
private String realname;
private String password;
private String sex;
}
Copy the code
Create the corresponding persistence layer (dao layer)
EmpDAO:
public interface EmpDAO {
List<Emp> findAll(a);
void save(Emp emp);
void delete(String id);
Emp find(String id);
void update(Emp emp);
}
Copy the code
5. Create the corresponding Mapper mapping file
<mapper namespace="com.xieyunjie.dao.EmpDAO">
<! -- Update employee information -->
<update id="update" parameterType="com.xieyunjie.entity.Emp">
update t_emp set name=#{name},salary=#{salary},age=#{age},bir=#{bir}
where id=#{id}
</update>
<! Select * from employee by id;
<select id="find" parameterType="String" resultType="com.xieyunjie.entity.Emp">
select id,name,salary,age,bir from t_emp
whereid=#{id}
</select>
<! -- Delete employee information -->
<delete id="delete" parameterType="String">
delete from t_emp where id=#{id}
</delete>
<! -- Save employee information -->
<insert id="save" parameterType="com.xieyunjie.entity.Emp">
insert into t_emp values(#{id},#{name},#{salary},#{age},#{bir})
</insert>
<! Select * from 'all';
<select id="findAll" resultType="com.xieyunjie.entity.Emp">
select id,name,salary,age,bir from t_emp
</select>
</mapper>
Copy the code
Create the corresponding business layer (service layer)
public interface EmpService {
List<Emp> findAll(a);
void save(Emp emp);
void delete(String id);
Emp find(String id);
void update(Emp emp);
}
Copy the code
@Service
@Transactional
public class EmpServiceImpl implements EmpService {
@Autowired
private EmpDAO empDAO;
@Override
public void update(Emp emp) {
empDAO.update(emp);
}
@Override
@Transactional(propagation = Propagation.SUPPORTS)
public Emp find(String id) {
return empDAO.find(id);
}
@Override
public void delete(String id) {
empDAO.delete(id);
}
@Override
public void save(Emp emp) {
emp.setId(UUID.randomUUID().toString());
empDAO.save(emp);
}
@Override
@Transactional(propagation = Propagation.SUPPORTS)
public List<Emp> findAll(a) {
returnempDAO.findAll(); }}Copy the code
7. Create a controller
@Controller
@RequestMapping("/emp")
public class EmpController {
@Autowired
private EmpService empService;
// Update the employee information method
@PostMapping("/update")
public String update(Emp emp){
empService.update(emp);
return "redirect:/emp/findAll";
}
//id query an employee
@GetMapping("/find")
public String find(String id, Model model){
Emp emp = empService.find(id);
model.addAttribute("emp",emp);
return "/ems/updateEmp";
}
// Delete an employee
@GetMapping("/delete")
public String delete(String id){
empService.delete(id);
return "redirect:/emp/findAll";
}
// Save the staff
@PostMapping("/save")
public String save(Emp emp){
empService.save(emp);
return "redirect:/emp/findAll";
}
// Query all
@GetMapping("/findAll")
public String findAll(Model model){
List<Emp> emps=empService.findAll();
model.addAttribute("emps",emps);
return "ems/emplist"; }}Copy the code
Create a utility class that generates the captcha
package com.xieyunjie.utils;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.Random;
public class ValidateImageCodeUtils {
/** * Verification code Difficulty Level Simple- digits Medium- digits and lowercase letters Hard- digits and lowercase letters */
public enum SecurityCodeLevel {
Simple, Medium, Hard
};
/** * Generates the default verification code, 4 bits of medium difficulty **@return* /
public static String getSecurityCode(a) {
return getSecurityCode(4, SecurityCodeLevel.Medium, false);
}
/** * Generates captcha ** of any length and difficulty@param length
* @param level
* @param isCanRepeat
* @return* /
public static String getSecurityCode(int length, SecurityCodeLevel level, boolean isCanRepeat) {
// Select len characters randomly
int len = length;
// set of characters (-- excluding confusable digits 0,1, letters l,o, o)
char[] codes = {
'0'.'1'.'2'.'3'.'4'.'5'.'6'.'7'.'8'.'9'.'a'.'b'.'c'.'d'.'e'.'f'.'g'.'h'.'i'.'j'.'k'.'l'.'m'.'n'.'o'.'p'.'q'.'r'.'s'.'t'.'u'.'v'.'w'.'x'.'y'.'z'.'A'.'B'.'C'.'D'.'E'.'F'.'G'.'H'.'I'.'J'.'K'.'L'.'M'.'N'.'O'.'P'.'Q'.'R'.'S'.'T'.'U'.'V'.'W'.'X'.'Y'.'Z'
};
// Intercepts the string according to the difficulty
if (level == SecurityCodeLevel.Simple) {
codes = Arrays.copyOfRange(codes, 0.10);
} else if (level == SecurityCodeLevel.Medium) {
codes = Arrays.copyOfRange(codes, 0.36);
}
// Character set and length
int n = codes.length;
Throw a runtime exception
if (len > n && isCanRepeat == false) {
throw new RuntimeException(String.format("Call SecurityCode. GetSecurityCode (% 1 $s % 2 $s, % 3 $s) abnormal," + "When isCanRepeat is %3$s, the passed argument %1$s cannot be greater than %4$s", len, level, isCanRepeat, n));
}
// Store the extracted characters
char[] result = new char[len];
// Check whether repeated characters occur
if (isCanRepeat) {
for (int i = 0; i < result.length; i++) {
// index 0 and n-1
int r = (int) (Math.random() * n);
// Set the ith element of result to the value stored by code[r]result[i] = codes[r]; }}else {
for (int i = 0; i < result.length; i++) {
// index 0 and n-1
int r = (int) (Math.random() * n);
// Set the ith element of result to the value stored by code[r]
result[i] = codes[r];
// We must make sure that we do not extract that character again. Here we rewrite code[r] with the last character in the array and change n-1
codes[r] = codes[n - 1]; n--; }}return String.valueOf(result);
}
/** * Generate captcha image *@param securityCode
* @return* /
public static BufferedImage createImage(String securityCode){
int codeLength = securityCode.length();// Verification code length
int fontSize = 18;// Font size
int fontWidth = fontSize+1;
// Image width and height
int width = codeLength*fontWidth+6;
int height = fontSize*2+1;
/ / picture
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g = image.createGraphics();
g.setColor(Color.WHITE);// Set the background color
g.fillRect(0.0, width, height);// Fill the background
g.setColor(Color.LIGHT_GRAY);// Set the border color
g.setFont(new Font("Arial", Font.BOLD, height-2));// Border font style
g.drawRect(0.0, width-1, height-1);// Draw the border
// Draw noise
Random rand = new Random();
g.setColor(Color.LIGHT_GRAY);
for (int i = 0; i < codeLength*6; i++) {
int x = rand.nextInt(width);
int y = rand.nextInt(height);
g.drawRect(x, y, 1.1);// Draw a 1 by 1 rectangle
}
// Draw the verification code
int codeY = height-10;
g.setColor(new Color(19.148.246));
g.setFont(new Font("Georgia", Font.BOLD, fontSize));
for(int i=0; i<codeLength; i++){double deg=new Random().nextDouble()*20;
g.rotate(Math.toRadians(deg), i*16+13,codeY-7.5);
g.drawString(String.valueOf(securityCode.charAt(i)), i*16+5, codeY);
g.rotate(Math.toRadians(-deg), i*16+13,codeY-7.5);
}
g.dispose();// Close the resource
return image;
}
public static void main(String[] args) throws IOException {
String securityCode = ValidateImageCodeUtils.getSecurityCode();
System.out.println(securityCode);
BufferedImage image = ValidateImageCodeUtils.createImage(securityCode);
ImageIO.write(image,"png".new FileOutputStream("aa.png")); }}Copy the code
9. Create corresponding front-end pages (and introduce corresponding resource files)
Due to the large amount of code, here will not be shown, want to source can leave a message, add my friends.
10. Test
The registration screen
After logging in (can be added, deleted and checked)
That’s all for today, thank you!