Spring boot項(xiàng)目搭建(前端到數(shù)據(jù)庫(kù),超詳細(xì)),大神勿進(jìn)!
前段時(shí)間,有很多小伙伴私下跟我說(shuō),想搞一個(gè)項(xiàng)目實(shí)戰(zhàn)。今天剛好我有空,于是,我就搞了一個(gè)從前端到后臺(tái)的用戶系統(tǒng)(demo)。用戶系統(tǒng)基本是所有項(xiàng)目中都必須有的基礎(chǔ)模塊,可大可小。大的需要很大一個(gè)團(tuán)隊(duì)來(lái)維護(hù),小的一個(gè)人兼職就能搞定。對(duì)于很多還未參與工作的同學(xué)來(lái)說(shuō),這個(gè)項(xiàng)目也可以練練手,說(shuō)不定,第一份工作進(jìn)去就是搞用戶模塊呢。
技術(shù)棧
Spring Boot 、Jpa 、Thymeleaf、HTML、Maven、MySQL。
對(duì)于技術(shù)棧,還不清楚的同學(xué),自行查找相關(guān)資料,至少知道個(gè)大概是干啥的。
需求功能
現(xiàn)在需要對(duì)用戶信息進(jìn)行新增、列表展示、用戶詳情展示、信息修改、信息刪除等功能。
用戶信息:姓名、密碼、手機(jī)號(hào)碼、年齡。
數(shù)據(jù)庫(kù)表
自己本地安裝MySQL,并創(chuàng)建數(shù)據(jù)庫(kù),然后在創(chuàng)建一張用戶表。
建表語(yǔ)句
- CREATE TABLE `user` (
- `uid` bigint NOT NULL AUTO_INCREMENT,
- `uname` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
- `password` varchar(6) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
- `tel` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
- `age` int DEFAULT NULL,
- PRIMARY KEY (`uid`)
- ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
項(xiàng)目構(gòu)建
項(xiàng)目整體目錄
接下來(lái),我們就一步一步,把這些代碼理清楚。
整體項(xiàng)目采用的是
- html-->controller--->service--repository-->DB
這也是當(dāng)前實(shí)際開(kāi)發(fā)中相對(duì)比較流行的,但為了演示,我這里就就用entity實(shí)體類就搞定了。
實(shí)際開(kāi)發(fā)中會(huì)有其他什么O之類的,比如說(shuō):DTO/VO/BO.....。有的項(xiàng)目使用的是DTO,有的可能使用的是BO等。進(jìn)入項(xiàng)目組了,按照項(xiàng)目組的開(kāi)發(fā)規(guī)范來(lái)就行了,實(shí)在不理解的話,建議你先學(xué)會(huì)模仿別人是怎么做的。
廢話不多說(shuō),直接開(kāi)干!
創(chuàng)建Spring Boot項(xiàng)目
可以使用spring官網(wǎng)給創(chuàng)建方式,地址:
https://start.spring.io/
這里也可以參考另外一篇文章:
如何快速構(gòu)建Spring Boot基礎(chǔ)項(xiàng)目?
maven依賴
在項(xiàng)目的pom.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>
- <!-- Spring Boot 項(xiàng)目 -->
- <parent>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-parent</artifactId>
- <version>2.1.6.RELEASE</version>
- </parent>
- <!-- 項(xiàng)目 maven 坐標(biāo) -->
- <groupId>com.tian.user</groupId>
- <artifactId>spring-boot-jpa-thymeleaf</artifactId>
- <version>1.0-SNAPSHOT</version>
- <!-- 項(xiàng)目名稱 -->
- <name>spring-boot-jpa-thymeleaf</name>
- <dependencies>
- <!-- web -->
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-web</artifactId>
- </dependency>
- <!-- thymeleaf -->
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-thymeleaf</artifactId>
- </dependency>
- <!-- jpa -->
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-data-jpa
- </artifactId>
- </dependency>
- <!-- MySQL -->
- <dependency>
- <groupId>mysql</groupId>
- <artifactId>mysql-connector-java</artifactId>
- </dependency>
- </dependencies>
- <build>
- <plugins>
- <plugin>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-maven-plugin</artifactId>
- <configuration>
- <fork>true</fork>
- </configuration>
- </plugin>
- </plugins>
- </build>
- </project>
主要是SpringBoot項(xiàng)目parent、web、MySQL、jpa、thymeleaf依賴,這樣就把相關(guān)的jar包給依賴進(jìn)來(lái)了。
啟動(dòng)類
- import org.springframework.boot.SpringApplication;
- import org.springframework.boot.autoconfigure.SpringBootApplication;
- import org.springframework.boot.builder.SpringApplicationBuilder;
- import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
- /**
- * @author java 后端技術(shù)全棧
- * 就是一個(gè)簡(jiǎn)單的啟動(dòng)類
- */
- @SpringBootApplication
- public class Application {
- public static void main(String[] args) {
- SpringApplication.run(Application.class, args);
- }
- }
注意:此時(shí)數(shù)據(jù)庫(kù)相關(guān)信息沒(méi)有配置進(jìn)項(xiàng)目里,所以,項(xiàng)目是啟動(dòng)不了的。
集成MySQL數(shù)據(jù)庫(kù)
在resource目錄下,創(chuàng)建一個(gè)application.properties文件,加入以下內(nèi)容:
- spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
- spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
- spring.datasource.username=root
- spring.datasource.password=123456
注意:如果MySQL是8.0版本,必須要配置服務(wù)時(shí)區(qū),否則會(huì)啟動(dòng)不了。
此時(shí)項(xiàng)目就可以正常啟動(dòng)了。
集成 Jpa
在application.properties中添加
- spring.jpa.properties.hibernate.hbm2dl.auto=create
- spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
- spring.jpa.show-sql=true
創(chuàng)建一個(gè)UserRepository
- package com.tian.user.repository;
- import com.tian.user.entity.User;
- import org.springframework.data.jpa.repository.JpaRepository;
- import org.springframework.data.jpa.repository.Modifying;
- import org.springframework.data.jpa.repository.Query;
- import org.springframework.stereotype.Repository;
- @Repository
- public interface UserRepository extends JpaRepository<User, Long> {
- }
這樣jpa就集成就來(lái)了。
集成Thymeleaf
前面我們已經(jīng)把jar包給以來(lái)進(jìn)來(lái)了,需要在application.properties中添加
- spring.thymeleaf.cache=false
- spring.thymeleaf.prefix=classpath:/templates/
- spring.thymeleaf.mode=.html
- spring.thymeleaf.encoding=UTF-8
- spring.thymeleaf.content-type=text/html
然后在resources目錄下添加兩個(gè)文件夾:
- templates 前端頁(yè)面模板目錄
- static 前端靜態(tài)資源目錄
新增用戶
在templates目錄下創(chuàng)建index.html
創(chuàng)建UserService接口和UserServiceImpl實(shí)現(xiàn)類。
- public interface UserService {
- void add(User user);
- }
- @Service
- public class UserServiceImpl implements UserService {
- @Resource
- private UserRepository userRepository;
- @Override
- public void add(User user) {
- userRepository.save(user);
- }
- }
創(chuàng)建UserController
- @Controller
- public class UserController {
- @Resource
- private UserService userService;
- @RequestMapping("/index")
- public String add(Model model) {
- return "index";
- }
- @RequestMapping("/save")
- public String save(Model model,User user) {
- userService.add(user);
- //跳轉(zhuǎn)到用戶列表
- return "redirect:/userList";
- }
- }
這樣一個(gè)新增功能我們就做完了。這里我們順帶著把用戶列表也給搞出來(lái)。
用戶列表
在templates目錄下創(chuàng)建user_list.html頁(yè)面
- <!DOCTYPE html>
- <html lang="zh" xmlns:th="http://www.thymeleaf.org">
- <head>
- <!-- 為了減少篇幅,樣式代碼這里就省略掉,樣式不是我們的重點(diǎn)內(nèi)容 -->
- </head>
- <body>
- <a href="/">
- <div id="ret">
- <button>新增用戶</button>
- </div>
- </a>
- <table id="content" style="border: 1px solid;">
- <tr>
- <th>姓名</th>
- <th>年齡</th>
- <th>手機(jī)號(hào)碼</th>
- <th>操作</th>
- </tr>
- <tr th:each="user:${users}">
- <td th:text="${user.uname}"></td>
- <td th:text="${user.age}"></td>
- <td th:text="${user.tel}"></td>
- <td><a th:href="@{'/userInfo/'+${user.uid}}" target="_blank">用戶詳情</a> |
- <a th:href="@{'/deleteById/'+${user.uid}}" target="_blank">刪除用戶信息</a> |
- <a th:href="@{'/update/'+${user.uid}}" target="_blank">修改用戶信息</a>
- </td>
- </tr>
- </table>
- </body>
- </html>
在service和實(shí)現(xiàn)類中添加用戶列表的方法,這里沒(méi)有做分頁(yè)。
- //UserService中添加
- List<User> findAll();
- //UserServiceImpl中添加方法
- @Override
- public List<User> findAll() {
- return userRepository.findAll();
- }
然后我們?cè)僭赾ontroller中添加一個(gè)方法用戶列表的方法。
- @RequestMapping("/userList")
- public String index(Model model) {
- List<User> users = userService.findAll();
- model.addAttribute("users", users);
- return "user_list";
- }
好了,自此用戶列表也搞定。下面我們來(lái)啟動(dòng)項(xiàng)目,然后演示一下:
演示
新增流程的演示,訪問(wèn):
http://localhost:8080/
來(lái)到新增用戶頁(yè)面:
填入用戶信息
點(diǎn)擊新增,來(lái)到用戶列表:
用戶詳情
在templates目錄下創(chuàng)建user_info.html頁(yè)面:
- <!DOCTYPE html>
- <html lang="zh" xmlns:th="http://www.thymeleaf.org">
- <head>
- <meta charset="UTF-8">
- <title>用戶詳情</title>
- </head>
- <body>
- <div id="content">
- 姓名:<input type="text" th:value="${user.uname}"><br/>
- 年齡:<input type="text" th:value="${user.age}"><br/>
- 密碼:<input type="text" th:value="${user.password}"><br/>
- 手機(jī)號(hào)碼:<input type="text" th:value="${user.tel}"><br/>
- </div>
- </body>
- </html>
在service和實(shí)現(xiàn)類分別添加相應(yīng)的方法。
- //UserService中添加方法
- User findById(Long id);
- //UserServiceImpl添加方法
- @Override
- public User findById(Long id) {
- return userRepository.getOne(id);
- }
然后在controller中添加方法
- @RequestMapping("/userInfo/{id}")
- public String userInfo(Model model, @PathVariable("id") Long id) {
- User user = userService.findById(id);
- model.addAttribute("user", user);
- return "user_info";
- }
然后再次啟動(dòng)項(xiàng)目,我們就直接可以從用戶列表中進(jìn)入到用戶詳情里。
點(diǎn)擊:用戶詳情。
OK,到此,用戶詳情也就搞定了。剩下的我們繼續(xù)搞修改功能。
用戶信息修改
在templates目錄下創(chuàng)建update.html頁(yè)面。
- <!DOCTYPE html>
- <html lang="zh" xmlns:th="http://www.thymeleaf.org">
- <head>
- <meta charset="UTF-8">
- <title>Index</title>
- </head>
- <body>
- <div id="content">
- <form action="/updateById" method="post">
- <input type="text" th:value="${user.uid}" name="uid"><br/>
- 姓名:<input type="text" th:value="${user.uname}" name="uname"><br/>
- 年齡:<input type="text" th:value="${user.age}" name="age"><br/>
- 密碼:<input type="text" th:value="${user.password}" name="password"><br/>
- 手機(jī)號(hào)碼:<input type="text" th:value="${user.tel}" name="tel"><br/>
- <button>修改</button>
- </form>
- </div>
- </body>
UserRepository中添加更新方法:
- @Repository
- public interface UserRepository extends JpaRepository<User, Long> {
- @Modifying
- @Query("update User u set u.tel=?1 ,u.uname=?2 , u.password=?3 where u.uid=?4")
- void updateById(String tel, String uname, String password, Long uid);
- }
繼續(xù)在UserService和實(shí)現(xiàn)類中添加想要的方法。
- //UserService中添加方法
- void update(User user);
- //UserServiceImpl中添加方法
- @Transactional
- @Override
- public void update(User user) {
- userRepository.updateById(user.getTel(), user.getUname(), user.getPassword(), user.getUid());
- }
注意:UserServiceImpl添加的 這個(gè)update方法,必須要事務(wù)注解@Transactional,否則更新失敗。異常信息如下:
- javax.persistence.TransactionRequiredException: Executing an update/delete query
- at org.hibernate.internal.AbstractSharedSessionContract.checkTransactionNeededForUpdateOperation(AbstractSharedSessionContract.java:398) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
加上事務(wù)注解@Transactional就搞定了。
然后在controller中添加方法
- @RequestMapping("/updateById")
- public String updateById(Model model,User user) {
- userService.update(user);
- return "redirect:/userList";
- }
- //跳轉(zhuǎn)到修改頁(yè)面
- @RequestMapping("/update/{id}")
- public String update(Model model, @PathVariable("id") Long id) {
- User user = userService.findById(id);
- model.addAttribute("user", user);
- return "update";
- }
再次啟動(dòng)項(xiàng)目,繼續(xù)來(lái)到用戶列表頁(yè)面:
點(diǎn)擊:修改用戶信息,然后跳轉(zhuǎn)到用戶信息修改頁(yè)面:
這里我們把手機(jī)尾號(hào)修改成666:
點(diǎn)擊修改按鈕。跳轉(zhuǎn)到用戶列表頁(yè)面:
發(fā)現(xiàn)此時(shí)的用戶手機(jī)號(hào)已經(jīng)修改完了。
到這里,我們已經(jīng)做了用戶新增、單個(gè)用戶信息查詢、多個(gè)用戶信息查詢、單個(gè)用戶信息修改。剩下的刪除功能留給大家自己去做。相信大家也是很輕松的就能完成的。
總結(jié)
本文使用了技術(shù)棧:
Spring Boot +Jpa + Thyneleaf +MySQL+Maven+HTML
實(shí)戰(zhàn)演練一個(gè)用戶信息新增、查詢、修改。
注意點(diǎn):
1、配置信息是一點(diǎn)要小心,不能有誤。
2、得自己安裝MySQL數(shù)據(jù)庫(kù),然后創(chuàng)建數(shù)據(jù)庫(kù),創(chuàng)建用戶表。
3、分層:html頁(yè)面、controller、service接口、service實(shí)現(xiàn)類、repository接口。
好了,一個(gè)簡(jiǎn)單的用戶信息模塊就這樣了,刪除就靠你們自己去實(shí)現(xiàn)了。非常簡(jiǎn)單的~,如有疑惑、問(wèn)題的可以隨時(shí)聯(lián)系我。
「展望」
后面我們基于這個(gè)不斷擴(kuò)大,比如:用戶信息刪除、用戶登錄、用戶注冊(cè)、權(quán)限、角色、集成Redis做緩存、使用Redis搞一個(gè)分布式鎖、用戶積分排行榜等待功能。
本文轉(zhuǎn)載自微信公眾號(hào)「Java后端技術(shù)全?!?,可以通過(guò)以下二維碼關(guān)注。轉(zhuǎn)載本文請(qǐng)聯(lián)系Java后端技術(shù)全棧公眾號(hào)。