springboot+mybatis+thymeleaf项目搭建及前后端交互
前言
spring boot簡化了spring的開發(fā), 開發(fā)人員在開發(fā)過程中省去了大量的配置, 方便開發(fā)人員后期維護(hù).
使用spring boot可以快速的開發(fā)出restful風(fēng)格微服務(wù)架構(gòu).
本文將詳細(xì)的介紹如何搭建一套spring boot 項(xiàng)目, 實(shí)現(xiàn)前后端交互.
開發(fā)工具 : IDEA? ,? jdk 8 , mysql
開發(fā)完成后目錄截圖 :
?
一. 新建項(xiàng)目
file-new-project-Spring Initializr
Project SDK選擇JDK1.8, 后面直接下一步就可以
?
項(xiàng)目新建完成, 我們可以看到初始的目錄結(jié)構(gòu), 修改pom.xml, 配置上項(xiàng)目開發(fā)需要的包. 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 配置文件, 連接數(shù)據(jù)庫.?
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&&characterEncoding=utf8 spring.datasource.username=root spring.datasource.password=123456 spring.datasource.driver-class-name=com.mysql.jdbc.Driverspring.thymeleaf.encoding=utf-8 spring.thymeleaf.cache=false spring.thymeleaf.mode=html5?
二.項(xiàng)目開發(fā)
1.新建bo包, 存放實(shí)體類bean.
2.新建controller包, 存放控制層類.
3.新建dao包, 存放操作類.
4.新建service包, 存放服務(wù)接口類和實(shí)現(xiàn)類.
新建完成, 項(xiàng)目結(jié)構(gòu)如下圖:
?
項(xiàng)目包新建完畢, 首先我們新增實(shí)體類, 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 , 新建接口實(shí)現(xiàn)類UserInterFace, 實(shí)現(xiàn)人員信息的查詢, 新增, 修改, 刪除. 實(shí)現(xiàn)類代碼如下:
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;@Overridepublic UserInfo getUserByCardno(String cardno){return ud.getUserByCardno(cardno);}@Overridepublic UserInfo getUserById(int id){return ud.getUserById(id);}@Overridepublic int getIntUser() {return 0;}@Overridepublic int insertUser(String cardno , String psname){log.info("UserInterFace insertUser info log start");return ud.insertUser(cardno,psname);}@Overridepublic List<UserInfo> getAllUser(){log.info("UserInterFace getAllUser info log start");return ud.getAllUser();}@Overridepublic int deleteById(int id){log.info("UserInterFace deleteById info log start");return ud.deleteById(id);}@Overridepublic int updateById(int id , String cardno , String psname){log.info("UserInterFace updateById info log start");return ud.updateByid(id,cardno,psname);} }注意: 接口實(shí)現(xiàn)類, 調(diào)用了DAO層的方法, 在dao包下新建UserDao類 , 實(shí)現(xiàn)與數(shù)據(jù)庫的交互, 代碼如下 :?
package com.example.dao;import com.example.bo.UserInfo; import org.apache.ibatis.annotations.*;import java.util.List;@Mapper public interface UserDao {/*** 通過主鍵id號(hào)碼查詢?nèi)藛T信息*/@Select("select * from person where id = #{id}")UserInfo getUserById(@Param("id") int id);/*** 通過身份證號(hào)碼查詢?nèi)藛T信息*/@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包中,? 新建測(cè)試類去調(diào)用接口, 測(cè)試能不能查到數(shù)據(jù). 測(cè)試類代碼如下:?
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();
}
}
修改 , 新建項(xiàng)目時(shí)生成的DemoApplication類,啟動(dòng)項(xiàng)目,修改代碼如下:
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);} }項(xiàng)目啟動(dòng)完成, 我們?cè)诰W(wǎng)頁輸入?http://localhost:8080/test/getUser ,? 既可以查到數(shù)據(jù)如下 :?
至此, 項(xiàng)目已經(jīng)可以從數(shù)據(jù)庫查詢數(shù)據(jù)返回到頁面, 但是返回的是一串字符. 我們?nèi)绾巫尫祷氐臄?shù)據(jù)在頁面以列表形式展示, 而且在頁面可以直接進(jìn)行增刪改查操作呢? 這就是我們接下來要說的了.?
首先在配置文件引入如下包, 最上面的配置文件里面已經(jīng)引入 .
<dependency><groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
然后在/resources/templates文件夾下面新建我們需要的頁面. 新建common文件夾,存放公共的頁面, 新建user文件夾, 存放人員相關(guān)頁面. 新建公共頁面success.html做為操作成功提示頁面.
新建form.html提交頁面, userlist.html列表展示頁面, userview.html詳細(xì)信息展示頁面. 新建完目錄如下 :
頁面代碼如下 :
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>證件號(hào)碼</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類, 來與頁面實(shí)現(xiàn)交互
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);@Autowiredprivate 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";}@PostMappingpublic 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";}}啟動(dòng)項(xiàng)目, 輸入網(wǎng)址?http://localhost:8080/user/userlist 查詢數(shù)據(jù), 顯示列表 :?
到此, 整個(gè)項(xiàng)目的搭建和代碼已經(jīng)完成.
?
總結(jié)
這是博主博客生涯的第一篇博客, 博客內(nèi)容有參考一些資料, 但代碼都是博主自己一行一行實(shí)現(xiàn) . 博文寫的不對(duì)或不好的地方可以提出意見, 大家一起進(jìn)步, 謝謝閱讀.?
轉(zhuǎn)載于:https://www.cnblogs.com/sunge-1134/p/9924045.html
總結(jié)
以上是生活随笔為你收集整理的springboot+mybatis+thymeleaf项目搭建及前后端交互的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 一次java导出pdf的经历
- 下一篇: Oracle 高水位问题