前言html
spring boot簡化了spring的開發, 開發人員在開發過程當中省去了大量的配置, 方便開發人員後期維護.html5
使用spring boot能夠快速的開發出restful風格微服務架構.java
本文將詳細的介紹如何搭建一套spring boot 項目, 實現先後端交互.mysql
開發工具 : IDEA , jdk 8 , mysqlweb
開發完成後目錄截圖 :spring
一. 新建項目sql
file-new-project-Spring Initializr數據庫
Project SDK選擇JDK1.8, 後面直接下一步就能夠apache
項目新建完成, 咱們能夠看到初始的目錄結構, 修改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&&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 查詢數據, 顯示列表 :
到此, 整個項目的搭建和代碼已經完成.
總結
這是博主博客生涯的第一篇博客, 博客內容有參考一些資料, 但代碼都是博主本身一行一行實現 . 博文寫的不對或很差的地方能夠提出意見, 你們一塊兒進步, 謝謝閱讀.