Spring boot+mybatis+thymeleaf 實(shí)現(xiàn)登錄注冊(cè)增刪改查功能的示例代碼
本文重在實(shí)現(xiàn)理解,過(guò)濾器,業(yè)務(wù),邏輯需求,樣式請(qǐng)無(wú)視。。
項(xiàng)目結(jié)構(gòu)如下

1.idea新建Spring boot項(xiàng)目,在pom中加上thymeleaf和mybatis支持。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> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.3.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.jz</groupId> <artifactId>table</artifactId> <version>0.0.1-SNAPSHOT</version> <name>table</name> <description>Demo project for Spring Boot</description> <properties> <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-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
2. 在項(xiàng)目resources目錄下新建mybatis文件夾,用于存放mybatis配置文件。 在 application.properties 中配置本地?cái)?shù)據(jù)源和mybatis配置文件地址, application.properties代碼如下
spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/student?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC spring.datasource.username=用戶(hù)名 spring.datasource.password=密碼 spring.jpa.showSql=true mybatis: mybatis.type-aliases-package=com.jz.table.entity mybatis.mapper-locations=mybatis/*.xml
com.mysql.cj.jdbc.Driver 是 mysql-connector-java 6中的,需要指定時(shí)區(qū)serverTimezone
2.2在啟動(dòng)類(lèi)上加上掃描的Dao包
package com.jz.table;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.jz.table.dao")
public class TableApplication {
public static void main(String[] args) {
SpringApplication.run(TableApplication.class, args);
}
}
3.數(shù)據(jù)庫(kù)建兩個(gè)表admin和userinfo用于登錄和操作用
2019.10.3 現(xiàn)在mysql不能用admin作為表名了,請(qǐng)注意一下


4.開(kāi)始寫(xiě)代碼
entity:實(shí)體代碼
1.Admin實(shí)體類(lèi)
package com.jz.table.entity;
public class Admin {
private Integer id;
private String name;
private Integer password;
private String job;
public Admin() {
}
public Admin(Integer id, String name, Integer password, String job) {
this.id = id;
this.name = name;
this.password = password;
this.job = job;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getPassword() {
return password;
}
public void setPassword(Integer password) {
this.password = password;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
}
2.UserInfo實(shí)體類(lèi)
package com.jz.table.entity;
public class UserInfo {
private Integer id;
private String name;
private Integer age;
private String sex;
public UserInfo() {
}
public UserInfo(Integer id, String name, Integer age, String sex) {
this.id = id;
this.name = name;
this.age = age;
this.sex = sex;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}
Dao層代碼
1.AdminDao
package com.jz.table.dao;
import com.jz.table.entity.Admin;
public interface AdminDao {
//登錄判斷
Admin login(Admin admin);
//注冊(cè)
int addAdmin(Admin admin);
}
2.UserDao
package com.jz.table.dao;
import com.jz.table.entity.UserInfo;
import java.util.List;
public interface UserDao {
//查
List<UserInfo> findall();
//增
int adduser(UserInfo user);
//根據(jù)Id查,用于修改時(shí)頁(yè)面回顯數(shù)據(jù)
UserInfo findByid(Integer id);
//修改
int updateUser(UserInfo user);
//刪除
int delUser(Integer id);
}
3.XML文件,因?yàn)闆](méi)有業(yè)務(wù)邏輯,service省了,controller中直接引入dao
1.AdminMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.jz.table.dao.AdminDao">
<select id="login" parameterType="com.jz.table.entity.Admin" resultType="com.jz.table.entity.Admin">
select name,job FROM admin WHERE name = #{name} AND password = #{password}
</select>
<insert id="addAdmin" parameterType="com.jz.table.entity.Admin">
INSERT INTO admin (name,password,job) VALUES (#{name},#{password},#{job});
</insert>
</mapper>
2.UserMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.jz.table.dao.UserDao">
<select id="findall" resultType="com.jz.table.entity.UserInfo">
select * from userinfo
</select>
<insert id="adduser" parameterType="com.jz.table.entity.UserInfo">
INSERT INTO userinfo(name,age,sex) VALUES (#{name},#{age},#{sex})
</insert>
<select id="findByid" parameterType="java.lang.Integer" resultType="com.jz.table.entity.UserInfo">
SELECT * FROM userinfo where id = #{id}
</select>
<update id="updateUser" parameterType="com.jz.table.entity.UserInfo">
update userinfo SET name=#{name },age =#{age},sex=#{sex} WHERE id = #{id}
</update>
<delete id="delUser" parameterType="java.lang.Integer">
DELETE from userinfo WHERE id = #{id}
</delete>
</mapper>
4.頁(yè)面,在templates文件夾下新建public和user文件夾用來(lái)存放公共頁(yè)面和user操作頁(yè)面
public文件夾下新建成功、失敗提示頁(yè)
1.success.html
<!DOCTYPE html> <!--引入thymeleaf--> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>操作成功提示頁(yè)</title> </head> <body> <h1>操作成功</h1> <a href="/index" rel="external nofollow" rel="external nofollow" > 返回首頁(yè)</a> </body> </html>
2.false.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>操作失敗提示頁(yè)</title>
<script th:src="@{/js/jquery-1.8.0.min.js}"></script>
</head>
<body>
<h1>操作失敗,請(qǐng)檢查數(shù)據(jù)重試</h1>
<input onclick="history.go(-1)" type="button" value="返回">
</body>
</html>
4.2在templates文件夾下新建login和register頁(yè)面作為登錄和注冊(cè)頁(yè)面
1.login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>首頁(yè)</title>
<style>
/*a標(biāo)簽去下劃線(xiàn)和點(diǎn)擊不變色,div內(nèi)容居中*/
a{
text-decoration: none;
color: #333333;
}
#idiv{text-align: center;border-radius: 20px;
width: 300px;
height: 350px;
margin: auto;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;}
</style>
</head>
<body>
<div id="idiv">
<form action="/gologin" method="post">
請(qǐng)輸入姓名<input id="name" name="name" required="required"><br><br>
請(qǐng)輸入密碼<input id="password" name="password" type="password" placeholder="僅支持正整數(shù)" required="required"><br><br>
<input type="submit" value="登錄"> <button> <a href="/goregister" rel="external nofollow" >注冊(cè)</a></button>
</form>
</div>
</body>
</html>
2.register.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>賬號(hào)注冊(cè)</title>
<script th:src="@{/js/jquery-1.8.0.min.js}"></script>
</head>
<body>
<h2>賬號(hào)注冊(cè)</h2>
請(qǐng)輸入姓名:<input type="text" id="name"/><br><br>
請(qǐng)輸入密碼:<input type="password" id="password" placeholder="僅支持整數(shù)" /><br><br>
請(qǐng)確認(rèn)密碼:<input type="password" id="passwordTwo" placeholder="僅支持整數(shù)"/><br><br>
請(qǐng)選擇角色:<select id="job" style="width: 173px">
<option value="管理員">管理員</option>
</select><br><br>
<button onclick="register()">注冊(cè)</button>
</body>
<script>
function register() {
var name = $("#name").val();
var password1 = $("#password").val();
var password2 = $("#passwordTwo").val();
var job = $("#job").val();
if (Number(password1) == Number(password2)){
$.post("/register",{name:name,password:password1,job:job},function (res) {
if (res ==true){
alert("注冊(cè)成功");
window.location.href ="/login";
} else {
alert("注冊(cè)失敗,請(qǐng)檢查數(shù)據(jù)重試");
}
})
}else {
alert("兩次密碼不一致!");
}
}
</script>
</html>
3.controller中代碼
@Controller
public class TestController {
@Resource
private AdminDao ad;
@Resource
private UserDao ud;
@RequestMapping("/login")//主頁(yè)
public String index(){
return "login";
}
@RequestMapping("/goregister")//去注冊(cè)頁(yè)面
public String goregister(){
return "register";
}
@RequestMapping("/register")//注冊(cè)
@ResponseBody
public boolean register(Admin admin){
int i = ad.addAdmin(admin);
if (i>0){
return true;
}else {
return false;
}
}
@RequestMapping("/gologin")//登錄獲取用戶(hù)信息存到seccion
public String gologin(Admin admin,HttpServletRequest request,Model model){
Admin aa = ad.login(admin);
if (aa==null){
return "public/false";
}
HttpSession session = request.getSession();
session.setAttribute("aname",admin.getName());
session.setAttribute("apassword",admin.getPassword());
List<UserInfo> userlist = ud.findall();
model.addAttribute("admin",aa);
model.addAttribute("alist",userlist);
return "user/index";
}
@RequestMapping("/index")//從其他頁(yè)面操作后返回列表頁(yè)面(重復(fù)登錄)
public String login(Admin admin,Model model,HttpServletRequest request){
HttpSession session = request.getSession();
admin.setName((String) session.getAttribute("aname"));
admin.setPassword((Integer) session.getAttribute("apassword"));
Admin aa = ad.login(admin);
List<UserInfo> userlist = ud.findall();
model.addAttribute("admin",aa);
model.addAttribute("alist",userlist);
return "user/index";
}
}
4.3user文件夾下新建index,addUser,updateUser頁(yè)面,作為主頁(yè),添加,修改頁(yè)面
1.index.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>首頁(yè)</title>
<style>a{text-decoration:none}</style>
<script th:src="@{/js/jquery-1.8.0.min.js}"></script>
</head>
<body>
歡迎你 :<input th:value="${admin.name}" style="border: none; outline: none"/><br><br><br><br>
<h2>人員信息維護(hù)</h2>
<table width="888" border="1">
<thead>
<tr>
<th>id</th>
<th>姓名</th>
<th>年齡</th>
<th>性別</th>
<th>操作</th>
</tr>
<tr th:each="user:${alist}">
<td align="center" th:text="${user.id}"></td>
<td align="center" th:text="${user.name}"></td>
<td align="center" th:text="${user.age}"></td>
<td align="center" th:text="${user.sex}"></td>
<td align="center"><a th:href="@{'/goupdate/'+${user.id}}" rel="external nofollow" >修改</a>
<a th:href="@{'/godel/'+${user.id}}" rel="external nofollow" >刪除</a>
</td>
</tr>
</thead>
</table>
<button><a href="/goadd" rel="external nofollow" >添加</a></button>
</body>
</html>
2.addUser.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>添加用戶(hù)</title>
<script th:src="@{/js/jquery-1.8.0.min.js}"></script>
</head>
<body>
<h2>我是添加頁(yè)面</h2>
請(qǐng)輸入姓名:<input id="name" name="name" type="text" /><br><br>
請(qǐng)輸入年齡:<input id="age" name="age" type="text" /><br><br>
請(qǐng)選擇性別:<select id="sex" name="sex" style="width: 173px">
<option value="男">男</option>
<option value="女">女</option>
</select><br><br>
<button onclick="goadd()" name="sub" id="sub">添加</button>
<button name="button" onclick="javascript:history.back(-1);">返回</button>
</body>
<script>
function goadd() {
var name = $("#name").val();
var age = $("#age").val();
var sex = $("#sex").val();
$.post("/addUser",{name:name,age:age,sex:sex},function (res) {
if (res==true){
alert("添加成功")
window.location.href ="/index";
}else {
alert("添加失敗,請(qǐng)檢查數(shù)據(jù)重試!");
}
})
}
</script>
</html>
3.updateUser.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>修改用戶(hù)</title>
<script th:src="@{/js/jquery-1.8.0.min.js}"></script>
</head>
<body>
<h2>這是修改頁(yè)面</h2>
<input type="hidden" id="id" th:value="${user.id}"><br><br>
請(qǐng)輸入姓名:<input id="name" th:value="${user.name}"/><br><br>
請(qǐng)輸入年齡:<input id="age" th:value="${user.age}"/><br><br>
請(qǐng)選擇性別:<select id="sex" style="width: 173px">
<option value="男">男</option>
<option value="女">女</option>
</select><br><br>
<button onclick="goupdate()">修改</button>
<button name="button" onclick="javascript:history.back(-1);">返回</button>
</body>
<script>
function goupdate() {
var id=$("#id").val();
var name = $("#name").val();
var age = $("#age").val();
var sex = $("#sex").val();
$.post("/update",{id:id,name:name,age:age,sex:sex},function (res) {
if (res==true) {
alert("修改成功");
window.location.href="/index" rel="external nofollow" rel="external nofollow" ;
}else {
alert("修改失敗,請(qǐng)檢查數(shù)據(jù)重試!");
}
})
}
</script>
</html>
4.controller中代碼
@RequestMapping("/goadd")//去添加頁(yè)面
public String goadd(){
return "user/addUser";
}
@RequestMapping("/addUser")//添加信息
@ResponseBody
public boolean addUser(UserInfo user){
int i = ud.adduser(user);
if (i>0){
return true;
}else {
return false;
}
}
@RequestMapping("/goupdate/{id}")//去修改頁(yè)面,回顯數(shù)據(jù)
public String goupdate(@PathVariable("id") int id,Model model){
UserInfo user = ud.findByid(id);
model.addAttribute("user",user);
return "user/updateUser";
}
@RequestMapping("/update")//修改
@ResponseBody
public boolean updateUser(UserInfo user){
int i = ud.updateUser(user);
if (i>0){
return true;
}else {
return false;
}
}
@RequestMapping("/godel/{id}")//刪除
public String delUser(@PathVariable("id") Integer id){
ud.delUser(id);
return "public/success";
}
5.完整controller代碼
package com.jz.table.controller;
import com.jz.table.dao.AdminDao;
import com.jz.table.dao.UserDao;
import com.jz.table.entity.Admin;
import com.jz.table.entity.UserInfo;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
@Controller
public class TestController {
@Resource
private AdminDao ad;
@Resource
private UserDao ud;
@RequestMapping("/login")//主頁(yè)
public String index(){
return "login";
}
@RequestMapping("/goregister")//去注冊(cè)頁(yè)面
public String goregister(){
return "register";
}
@RequestMapping("/register")//注冊(cè)
@ResponseBody
public boolean register(Admin admin){
int i = ad.addAdmin(admin);
if (i>0){
return true;
}else {
return false;
}
}
@RequestMapping("/gologin")//登錄獲取用戶(hù)信息存到seccion
public String gologin(Admin admin,HttpServletRequest request,Model model){
Admin aa = ad.login(admin);
if (aa==null){
return "public/false";
}
HttpSession session = request.getSession();
session.setAttribute("aname",admin.getName());
session.setAttribute("apassword",admin.getPassword());
List<UserInfo> userlist = ud.findall();
model.addAttribute("admin",aa);
model.addAttribute("alist",userlist);
return "user/index";
}
@RequestMapping("/index")//從其他頁(yè)面操作后返回列表頁(yè)面(重復(fù)登錄)
public String login(Admin admin,Model model,HttpServletRequest request){
HttpSession session = request.getSession();
admin.setName((String) session.getAttribute("aname"));
admin.setPassword((Integer) session.getAttribute("apassword"));
Admin aa = ad.login(admin);
List<UserInfo> userlist = ud.findall();
model.addAttribute("admin",aa);
model.addAttribute("alist",userlist);
return "user/index";
}
@RequestMapping("/goadd")//去添加頁(yè)面
public String goadd(){
return "user/addUser";
}
@RequestMapping("/addUser")//添加信息
@ResponseBody
public boolean addUser(UserInfo user){
int i = ud.adduser(user);
if (i>0){
return true;
}else {
return false;
}
}
@RequestMapping("/goupdate/{id}")//去修改頁(yè)面,回顯數(shù)據(jù)
public String goupdate(@PathVariable("id") int id,Model model){
UserInfo user = ud.findByid(id);
model.addAttribute("user",user);
return "user/updateUser";
}
@RequestMapping("/update")//修改
@ResponseBody
public boolean updateUser(UserInfo user){
int i = ud.updateUser(user);
if (i>0){
return true;
}else {
return false;
}
}
@RequestMapping("/godel/{id}")//刪除
public String delUser(@PathVariable("id") Integer id){
ud.delUser(id);
return "public/success";
}
}
效果如圖


到此這篇關(guān)于Spring boot+mybatis+thymeleaf 實(shí)現(xiàn)登錄注冊(cè)增刪改查功能的示例代碼的文章就介紹到這了,更多相關(guān)Spring boot mybatis thymeleaf 登錄注冊(cè)增刪改查內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- Servlet+MyBatis項(xiàng)目轉(zhuǎn)Spring Cloud微服務(wù),多數(shù)據(jù)源配置修改建議
- MyBatis實(shí)現(xiàn)注冊(cè)及獲取Mapper
- SpringBoot+Mybatis使用Mapper接口注冊(cè)的幾種方式
- SpringBoot+Mybatis實(shí)現(xiàn)登錄注冊(cè)的示例代碼
- IDEA下創(chuàng)建SpringBoot+MyBatis+MySql項(xiàng)目實(shí)現(xiàn)動(dòng)態(tài)登錄與注冊(cè)功能
- Spring MVC+mybatis實(shí)現(xiàn)注冊(cè)登錄功能
- Mybatis與微服務(wù)注冊(cè)的詳細(xì)過(guò)程
相關(guān)文章
舉例說(shuō)明Java設(shè)計(jì)模式編程中ISP接口隔離原則的使用
這篇文章主要介紹了Java設(shè)計(jì)模式編程中ISP接口隔離原則的使用,接口隔離原則主張一個(gè)類(lèi)對(duì)另外一個(gè)類(lèi)的依賴(lài)性應(yīng)當(dāng)是建立在最小的接口上,需要的朋友可以參考下2016-02-02
SpringBoot如何實(shí)現(xiàn)分離資源文件并打包
這篇文章主要介紹了SpringBoot如何實(shí)現(xiàn)分離資源文件并打包,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-06-06
MyBatis-Plus如何關(guān)閉SQL日志打印詳解
在使用mybatisplus進(jìn)行開(kāi)發(fā)時(shí),日志是一個(gè)非常有用的工具,它可以幫助我們更好地了解和調(diào)試我們的代碼,這篇文章主要給大家介紹了關(guān)于MyBatis-Plus如何關(guān)閉SQL日志打印的相關(guān)資料,需要的朋友可以參考下2024-03-03
Mybatis之解決collection一對(duì)多問(wèn)題(顯示的結(jié)果沒(méi)有整合到一起)
這篇文章主要介紹了Mybatis之解決collection一對(duì)多問(wèn)題(顯示的結(jié)果沒(méi)有整合到一起),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-03-03
http協(xié)議進(jìn)階之Transfer-Encoding和HttpCore實(shí)現(xiàn)詳解
這篇文章主要給大家介紹了http協(xié)議之Transfer-Encoding和HttpCore實(shí)現(xiàn)的相關(guān)資料,文中介紹的非常詳細(xì),相信對(duì)大家具有一定的參考價(jià)值,需要的朋友們下面來(lái)一起看看吧。2017-04-04
Java的BigDecimal在math包中提供的API類(lèi)場(chǎng)景使用詳解
這篇文章主要介紹了Java的BigDecimal在math包中提供的API類(lèi)場(chǎng)景使用詳解,BigDecimal,用來(lái)對(duì)超過(guò)16位有效位的數(shù)進(jìn)行精確的運(yùn)算,雙精度浮點(diǎn)型變量double可以處理16位有效數(shù),在實(shí)際應(yīng)用中,需要對(duì)更大或者更小的數(shù)進(jìn)行運(yùn)算和處理,需要的朋友可以參考下2023-12-12
一篇文章帶你了解mybatis的動(dòng)態(tài)SQL
這篇文章主要為大家介紹了mybatis的動(dòng)態(tài)SQL?,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來(lái)幫助2022-01-01

