SpringBoot整合thymeleaf簡單的CRUD

SpringBoot整合thymeleaf簡單的CRUD

最近發現以前學習的東西好多都忘記了,這裏開始天天記錄一點以前學習過的東西,今天就從最簡單的CRUD開始吧。前端

1、老規矩仍是先看看相應的目錄結構

1
2

2、添加相應的pom依賴

<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>
            <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-boot-starter</artifactId>
            <version>2.1.1</version>
        </dependency>

        <!--druid-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.21</version>
        </dependency>

3、建立對應的實體類

Emp:java

@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class Emp {
    private String id;
    private String name;
    private Double salary;
    private Integer age;
    private Date bir;

}

User:mysql

@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class User {
    private String id;
    private String username;
    private String realname;
    private String password;
    private String sex;

}

4、建立對應的持久層(即dao層)

EmpDAO:web

public interface EmpDAO {

    List<Emp> findAll();

    void save(Emp emp);

    void delete(String id);

    Emp find(String id);

    void update(Emp emp);
}

5、建立對應的Mapper映射文件

<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.xieyunjie.dao.EmpDAO">
    <!--更新員工信息-->
    <update id="update" parameterType="com.xieyunjie.entity.Emp">
        update t_emp set name=#{name},salary=#{salary},age=#{age},bir=#{bir}
        where id=#{id}
    </update>

    <!--根據id查詢員工-->
    <select id="find" parameterType="String" resultType="com.xieyunjie.entity.Emp">
        select id,name,salary,age,bir from t_emp
        whereid=#{id}
    </select>

    <!--刪除員工信息-->
    <delete id="delete" parameterType="String">
        delete from t_emp where id=#{id}
    </delete>

    <!--保存員工信息-->
    <insert id="save" parameterType="com.xieyunjie.entity.Emp">
        insert into t_emp values(#{id},#{name},#{salary},#{age},#{bir})
    </insert>

    <!--查詢全部-->
    <select id="findAll" resultType="com.xieyunjie.entity.Emp">
        select id,name,salary,age,bir from t_emp
    </select>

</mapper>

6、建立對應的業務層(即service層)

public interface EmpService {

    List<Emp> findAll();

    void save(Emp emp);

    void delete(String id);

    Emp find(String id);

    void update(Emp emp);
}
@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() {
        return empDAO.findAll();
    }
}

7、建立控制器

@Controller
@RequestMapping("/emp")
public class EmpController {

    @Autowired
    private EmpService empService;

    //更新員工信息方法
    @PostMapping("/update")
    public String update(Emp emp){
        empService.update(emp);
        return "redirect:/emp/findAll";
    }

    //id查詢員工
    @GetMapping("/find")
    public String find(String id, Model model){
        Emp emp = empService.find(id);
        model.addAttribute("emp",emp);
        return "/ems/updateEmp";
    }

    //刪除員工
    @GetMapping("/delete")
    public String delete(String id){
        empService.delete(id);
        return "redirect:/emp/findAll";
    }

    //保存員工
    @PostMapping("/save")
    public String save(Emp emp){
        empService.save(emp);
        return "redirect:/emp/findAll";
    }

    //查詢全部
    @GetMapping("/findAll")
    public String findAll(Model model){
        List<Emp> emps=empService.findAll();
        model.addAttribute("emps",emps);
        return "ems/emplist";
    }
}

8、建立生成驗證碼的工具類

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 {
    /**
     * 驗證碼難度級別 Simple-數字 Medium-數字和小寫字母 Hard-數字和大小寫字母
     */
    public enum SecurityCodeLevel {
        Simple, Medium, Hard
    };
    /**
     * 產生默認驗證碼,4位中等難度
     *
     * @return
     */
    public static String getSecurityCode() {
        return getSecurityCode(4, SecurityCodeLevel.Medium, false);
    }
    /**
     * 產生長度和難度任意的驗證碼
     *
     * @param length
     * @param level
     * @param isCanRepeat
     * @return
     */
    public static String getSecurityCode(int length, SecurityCodeLevel level, boolean isCanRepeat) {
        // 隨機抽取len個字符
        int len = length;
        // 字符集合(--除去易混淆的數字0,1,字母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'
        };
        // 根據不一樣難度截取字符串
        if (level == SecurityCodeLevel.Simple) {
            codes = Arrays.copyOfRange(codes, 0, 10);
        } else if (level == SecurityCodeLevel.Medium) {
            codes = Arrays.copyOfRange(codes, 0, 36);
        }
        // 字符集和長度
        int n = codes.length;
        // 拋出運行時異常
        if (len > n && isCanRepeat == false) {
            throw new RuntimeException(String.format("調用SecurityCode.getSecurityCode(%1$s,%2$s,%3$s)出現異常," + "當isCanRepeat爲%3$s時,傳入參數%1$s不能大於%4$s", len, level, isCanRepeat, n));
        }
        // 存放抽取出來的字符
        char[] result = new char[len];
        // 判斷可否出現重複字符
        if (isCanRepeat) {
            for (int i = 0; i < result.length; i++) {
                // 索引0 and n-1
                int r = (int) (Math.random() * n);
                // 將result中的第i個元素設置爲code[r]存放的數值
                result[i] = codes[r];
            }
        } else {
            for (int i = 0; i < result.length; i++) {
                // 索引0 and n-1
                int r = (int) (Math.random() * n);
                // 將result中的第i個元素設置爲code[r]存放的數值
                result[i] = codes[r];
                // 必須確保不會再次抽取到那個字符,這裏用數組中最後一個字符改寫code[r],並將n-1
                codes[r] = codes[n - 1];
                n--;
            }
        }
        return String.valueOf(result);
    }
    /**
     * 生成驗證碼圖片

     * @param securityCode

     * @return

     */
    public static BufferedImage createImage(String securityCode){

        int codeLength = securityCode.length();//驗證碼長度

        int fontSize = 18;//字體大小

        int fontWidth = fontSize+1;

        //圖片寬高

        int width = codeLength*fontWidth+6;
        int height = fontSize*2+1;
        //圖片

        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        Graphics2D g = image.createGraphics();

        g.setColor(Color.WHITE);//設置背景色

        g.fillRect(0, 0, width, height);//填充背景

        g.setColor(Color.LIGHT_GRAY);//設置邊框顏色

        g.setFont(new Font("Arial", Font.BOLD, height-2));//邊框字體樣式

        g.drawRect(0, 0, width-1, height-1);//繪製邊框

        //繪製噪點

        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);//繪製1*1大小的矩形

        }

        //繪製驗證碼

        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();//關閉資源
        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"));
    }
    
    
}

9、建立對應的前端頁面(而且引入相應的資源文件)

因爲代碼量較大,這裏就再也不進行展現,想要源碼的能夠留言,加我好友。spring

10、進行測試

5
註冊界面
6
登錄進來後(能夠進行增刪查改)
7
今天的大概就說到這兒,謝謝你們!sql

你們沒事能夠看看個人我的博客,謝謝!天涯志

相關文章
相關標籤/搜索