1. 程式人生 > >springboot+mybatis+thymeleaf專案搭建及前後端互動

springboot+mybatis+thymeleaf專案搭建及前後端互動

前言

spring boot簡化了spring的開發, 開發人員在開發過程中省去了大量的配置, 方便開發人員後期維護.

使用spring boot可以快速的開發出restful風格微服務架構.

本文將詳細的介紹如何搭建一套spring boot 專案, 實現前後端互動.

開發工具 : IDEA  ,  jdk 8 , mysql

開發完成後目錄截圖 :

 

一. 新建專案

file-new-project-Spring Initializr

Project SDK選擇JDK1.8, 後面直接下一步就可以

 

專案新建完成, 我們可以看到初始的目錄結構, 修改pom.xml, 配置上專案開發需要的包. xml配置如下 : 

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId
>com.example</groupId> <artifactId>demo</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>demo</name> <description>Demo project for Spring Boot</description> <parent> <
groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.6.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-logging</artifactId> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.1.1</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.21</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>

 修改application.properties 配置檔案, 連線資料庫. 

spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&amp&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

spring.thymeleaf.encoding=utf-8
spring.thymeleaf.cache=false
spring.thymeleaf.mode=html5

 

二.專案開發

1.新建bo包, 存放實體類bean.

2.新建controller包, 存放控制層類.

3.新建dao包, 存放操作類.

4.新建service包, 存放服務介面類和實現類.

新建完成, 專案結構如下圖:

 

專案包新建完畢, 首先我們新增實體類, UserInfo

package com.example.bo;

public class UserInfo {

    private String psname;
    private String cardno;
    private int id;

    public void setId(int id) {
        this.id = id;
    }

    public void setCardno(String cardno) {
        this.cardno = cardno;
    }

    public void setPsname(String psname) {
        this.psname = psname;
    }

    public String getPsname() {
        return psname;
    }

    public String getCardno() {
        return cardno;
    }

    public int getId() {
        return id;
    }
}

 

在我們之前新建的介面包裡新增介面IUserInterFace , 新建介面實現類UserInterFace, 實現人員資訊的查詢, 新增, 修改, 刪除. 實現類程式碼如下:

package com.example.service.impl;

import com.example.bo.UserInfo;
import com.example.dao.UserDao;
import com.example.service.IUserInterFace;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.slf4j.LoggerFactory;
import org.slf4j.Logger;

import java.util.List;

@Service
public class UserInterFace implements IUserInterFace {

    private final Logger log = LoggerFactory.getLogger(UserInterFace.class);

    @Autowired UserDao ud;
    @Override
    public UserInfo getUserByCardno(String cardno){
        return ud.getUserByCardno(cardno);
    }

    @Override
    public UserInfo getUserById(int id){
        return ud.getUserById(id);
    }

    @Override
    public int getIntUser() {
        return 0;
    }

    @Override
    public int insertUser(String cardno , String psname){
        log.info("UserInterFace insertUser info log start");
        return ud.insertUser(cardno,psname);
    }

    @Override
    public List<UserInfo> getAllUser(){
        log.info("UserInterFace getAllUser info log start");
        return ud.getAllUser();
    }

    @Override
    public int deleteById(int id){
        log.info("UserInterFace deleteById info log start");
        return ud.deleteById(id);
    }

    @Override
    public int updateById(int id , String cardno , String psname){
        log.info("UserInterFace updateById info log start");
        return ud.updateByid(id,cardno,psname);
    }
}

注意: 介面實現類, 呼叫了DAO層的方法, 在dao包下新建UserDao類 , 實現與資料庫的互動, 程式碼如下 : 

package com.example.dao;

import com.example.bo.UserInfo;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface UserDao {

    /**
     * 通過主鍵id號碼查詢人員資訊
     */
    @Select("select * from person where id = #{id}")
    UserInfo getUserById(@Param("id") int id);

    /**
     * 通過身份證號碼查詢人員資訊
     */
    @Select("select * from person where cardno = #{cardno}")
    UserInfo getUserByCardno(@Param("cardno") String cardno);

    /**
     * 新增人員資訊
     */
    @Insert("insert into person(cardno,psname) values(#{cardno},#{psname})")
    int insertUser(@Param("cardno") String cardno, @Param("psname") String psname);

    /**
     * 查詢所有人員資訊
     */
    @Select("select * from person")
    List<UserInfo> getAllUser();

    /**
     * 通過id刪除人員資訊
     */
    @Delete("delete from person where id = #{id}")
    int deleteById(@Param("id") int id);

    @Update("update person set cardno=#{cardno},psname=#{psname} where id=#{id}")
    int updateByid(@Param("id") int id , @Param("cardno") String cardno,@Param("psname") String psname);
}

在controller包中,  新建測試類去呼叫介面, 測試能不能查到資料. 測試類程式碼如下: 

package com.example.controller;

import com.example.service.IUserInterFace;
import com.example.bo.UserInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping(value = "/test")
public class TestUserController {

private final Logger log = LoggerFactory.getLogger(TestUserController.class);

@Autowired
private IUserInterFace iuser;

@RequestMapping("/num")
@ResponseBody
int home(){
int i = iuser.getIntUser();
return i;
}

@RequestMapping("/getUser")
@ResponseBody
List<UserInfo> getUser(){
//列印日誌
log.info("TestUserController getUser info");
return iuser.getAllUser();
}
}

修改 , 新建專案時生成的DemoApplication類,啟動專案,修改程式碼如下:

package com.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;

@EnableAutoConfiguration
@ComponentScan(basePackages={"com.example"})
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

專案啟動完成, 我們在網頁輸入 http://localhost:8080/test/getUser ,  既可以查到資料如下 : 

至此, 專案已經可以從資料庫查詢資料返回到頁面, 但是返回的是一串字元. 我們如何讓返回的資料在頁面以列表形式展示, 而且在頁面可以直接進行增刪改查操作呢? 這就是我們接下來要說的了. 

首先在配置檔案引入如下包, 最上面的配置檔案裡面已經引入 .

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

然後在/resources/templates資料夾下面新建我們需要的頁面. 新建common資料夾,存放公共的頁面, 新建user資料夾, 存放人員相關頁面. 新建公共頁面success.html做為操作成功提示頁面.

新建form.html提交頁面, userlist.html列表展示頁面, userview.html詳細資訊展示頁面. 新建完目錄如下 :

頁面程式碼如下 :

form.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
      xmlns:layout= "http://www.ultraq.net.nz/thymeleaf/layout">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form action="/user" th:action="@{/user}" method="post" th:object="${user}">
        <input type="hidden" name="id" th:value="*{id}">
        名字<br/>
        <input type="text" name="psname" th:value="*{psname}">
        <br/>
        <input type="text" name="cardno" th:value="*{cardno}">
        <br/>
        <input type="submit" value="提交">
    </form>
</body>
</html>

userlist.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta content="text/html;charset=UTF-8"/>
    <title>Content</title>
</head>
<body>
<div>
    <a href="/user/form" th:href="@{/user/form}">
        新建使用者
    </a>
</div>
<table border="2">
    <thead>
        <tr>
            <td>id</td>
            <td>名字</td>
            <td>證件號碼</td>
            <td>管理</td>
        </tr>
        <tr th:each="user:${contents}">
            <td th:text="${user.id}"></td>
            <td th:text="${user.psname}"></td>
            <td><a th:href="@{'/user/'+${user.id}}" th:text="${user.cardno}"></a></td>
            <td><a th:href="@{'/user/delete/'+${user.id}}">刪除</a></td>
        </tr>
    </thead>
</table>

</body>
</html>

userview.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <div>
        <p><strong>ID:</strong><span th:text="${user.id}"></span></p>
        <p><strong>名字:</strong><span th:text="${user.cardno}"></span></p>
        <p><strong>年齡:</strong><span th:text="${user.psname}"></span></p>
    </div>
    <div>
        <a th:href="@{'/user/delete/'+${user.id}}">刪除</a>
        <a th:href="@{'/user/edit/'+${user.id}}">修改</a>
    </div>
</body>
</html>

至此, 頁面新增完成 , 我們需要新增ThymeleafUserController類, 來與頁面實現互動

package com.example.controller;

import com.example.bo.UserInfo;
import com.example.service.IUserInterFace;
import org.slf4j.LoggerFactory;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping(value = "/user")
public class ThymeleafUserController {
    private final Logger log = LoggerFactory.getLogger(ThymeleafUserController.class);

    @Autowired
    private IUserInterFace iuser;

    @GetMapping("/userlist")
    public String userList(Model model){
        //列印日誌
        log.info("ThymeleafUserController userList info log start");
        model.addAttribute("contents",iuser.getAllUser());
        return "/user/userlist";
    }

    @GetMapping("/form")
    public String form(Model model){
        log.info("ThymeleafUserController form info log start");
        model.addAttribute("user" , new UserInfo());
        return "/user/form";
    }

    @GetMapping("{id}")
    public String userview(@PathVariable("id") int id , Model model){
        UserInfo user = iuser.getUserById(id);
        model.addAttribute("user",user);
        return "/user/userview";
    }

    @PostMapping
    public String saveUser(UserInfo user){
        log.info("ThymeleafUserController saveUser info log start");
        if(user.getId()==0){
            iuser.insertUser(user.getCardno(),user.getPsname());
        }else{
            int a = iuser.updateById(user.getId(),user.getCardno(),user.getPsname());
        }
        return "/common/success";
    }

    @GetMapping(value = "edit/{id}")
    public String editForm(@PathVariable("id") int id , Model model){
        log.info("ThymeleafUserController editForm info log start");
        UserInfo user = iuser.getUserById(id);
        model.addAttribute("user" , user);
        return "/user/form";
    }

    @GetMapping(value = "delete/{id}")
    public String delete(@PathVariable("id") int id){
        iuser.deleteById(id);
        return "/common/success";
    }

}

啟動專案, 輸入網址 http://localhost:8080/user/userlist 查詢資料, 顯示列表 : 

到此, 整個專案的搭建和程式碼已經完成.

 

總結

這是博主部落格生涯的第一篇部落格, 部落格內容有參考一些資料, 但程式碼都是博主自己一行一行實現 . 博文寫的不對或不好的地方可以提出意見, 大家一起進步, 謝謝閱讀.