文章目錄
1. 新建一個maven項目
1.1 編寫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>1.5.20.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>com.extsystem</groupId>
<artifactId>ExtSystem</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>ExtSystem</name>
<description>擴展系統</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>
<!-- springboot約定大於配置:thymleaf約定 -->
<!-- 1.默認靜態文件js、css、jsp等放在resources下面的static文件下 -->
<!-- 2.頁面文件放在templates文件下 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!-- <dependency> -->
<!-- <groupId>org.springframework.boot</groupId> -->
<!-- <artifactId>spring-boot-starter-data-jpa</artifactId> -->
<!-- </dependency> -->
<!-- <dependency> -->
<!-- <groupId>com.microsoft.sqlserver</groupId> -->
<!-- <artifactId>mssql-jdbc</artifactId> -->
<!-- <scope>runtime</scope> -->
<!-- </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. 編寫login登錄頁面
2.1 html代碼
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8" />
<title>登錄</title>
<!-- <link href="/css/bootstrap.min.css" rel="stylesheet"> -->
<!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
<link rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"
crossorigin="anonymous" />
<!-- 可選的 Bootstrap 主題文件(一般不用引入) -->
<link rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap-theme.min.css"
integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp"
crossorigin="anonymous" />
<!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
<script
src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js"
integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa"
crossorigin="anonymous"></script>
</head>
<body>
<div class="container">
<form action="login_in" method="post" class="form-horizontal"
role="form">
<div class="form-group">
<h2 class="col-sm-offset-5 col-sm-4">用戶登錄</h2>
</div>
<div class="form-group">
<label for="username" class="col-sm-offset-3 col-sm-2 control-label">用戶名:</label>
<div class="col-sm-3">
<input type="text" class="form-control" id="username"
name="username" placeholder="請輸入用戶名" />
</div>
</div>
<div class="form-group">
<label for="password" class="col-sm-offset-3 col-sm-2 control-label">密碼:</label>
<div class="col-sm-3">
<input type="text" class="form-control" id="password"
name="password" placeholder="請輸入密碼" />
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-5 col-sm-4">
<button type="submit" class="btn btn-default">登錄</button>
</div>
</div>
</form>
</div>
<!-- <script src="/js/jquery-2.2.1.min.js"></script> -->
<!-- <script src="/js/bootstrap.min.js"></script> -->
</body>
</html>
2.2. 使用webjars管理靜態資源文件(css/js等) - 推薦
SpringBoot項目搭建:使用WebJars統一管理靜態資源
2.2. 使用bootstrap(CDN)代替bootstrap.css和js文件
Bootstrap 中文網 爲 Bootstrap 專門構建了免費的 CDN 加速服務,訪問速度更快、加速效果更明顯、沒有速度和帶寬限制、永久免費。BootCDN 還對大量的前端開源工具庫提供了 CDN 加速服務。
<!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- 可選的 Bootstrap 主題文件(一般不用引入) -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
3. 編寫一個Controller.java
3.1. 寫一個LoginController
package com.extSystem.Login;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping(value = "/login")
public class LoginController {
@RequestMapping("/normalLogin")
public String normalLogin() {
// 因爲引入thympleaf,所以只需要傳入字符串自動到templates找相應頁面文件
return "login";
}
}
4. 集成數據庫
4.1. 集成mybatis
4.1.1. 添加相關依賴
<!-- 加入mybatis + mysqljdbc + druid(alibaba)依賴 -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>RELEASE</version>
</dependency>
<!-- 分頁插件 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.3</version>
</dependency>
4.1.2. 更改application.yml中的配置
spring:
application:
name: myspringboot
output:
ansi:
enabled: always
profiles:
active: dev
thymeleaf:
encoding: UTF-8
prefix: classpath:/templates/
server:
tomcat:
uri-encoding: UTF-8
max-connections: 500
min-spare-threads: 25
max-threads: 300
accept-count: 200
port: 8080
mybatis:
type-aliases-package: com.zb.mapper
mapper-locations: classpath:mapping/*.xml
pagehelper:
helper-dialect: mysql
reasonable: true
support-methods-arguments: true
params: count=countSql
logging:
level:
com.zb.mapper: debug
---
#開發配置
spring:
profiles: dev
datasource:
url: jdbc:mysql://localhost:3306/zb_db?useUnicode=true&characterEncoding=utf8&autoReconnect=true&failOverReadOnly=false&useSSL=false
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
filters: stat
maxActive: 20
initialSize: 1
maxWait: 60000
minIdle: 1
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: select 'x'
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
maxOpenPreparedStatements: 20
4.1.3. 建表
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(255) DEFAULT NULL,
`password` varchar(255) DEFAULT NULL,
`mobile` varchar(255) DEFAULT NULL,
`email` varchar(255) DEFAULT NULL,
`sex` varchar(255) DEFAULT NULL,
`nickname` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
insert into `user`(id, username, password, mobile, email,sex, nickname) VALUES(1, 'admin', '123456', '13918891675','[email protected]', '男', '管理員');
insert into `user`(id, username, password, mobile, email,sex, nickname) VALUES(2, 'lisi2', '123456', '13918891675','[email protected]', 'm', 'lisi1');
insert into `user`(id, username, password, mobile, email,sex, nickname) VALUES(3, 'lisi3', '123456', '13918891675','[email protected]', 'm', 'lisi1');
insert into `user`(id, username, password, mobile, email,sex, nickname) VALUES(4, 'lisi4', '123456', '13918891675','[email protected]', 'm', 'lisi1');
insert into `user`(id, username, password, mobile, email,sex, nickname) VALUES(5, 'lisi5', '123456', '13918891675','[email protected]', 'm', 'lisi1');
insert into `user`(id, username, password, mobile, email,sex, nickname) VALUES(6, 'lisi6', '123456', '13918891675','[email protected]', 'm', 'lisi1');
insert into `user`(id, username, password, mobile, email,sex, nickname) VALUES(7, 'lisi7', '123456', '13918891675','[email protected]', 'm', 'lisi1');
insert into `user`(id, username, password, mobile, email,sex, nickname) VALUES(8, 'lisi8', '123456', '13918891675','[email protected]', 'm', 'lisi1');
insert into `user`(id, username, password, mobile, email,sex, nickname) VALUES(9, 'lisi9', '123456', '13918891675','[email protected]', 'm', 'lisi1');
insert into `user`(id, username, password, mobile, email,sex, nickname) VALUES(10, 'lisi10', '123456', '13918891675','[email protected]', 'm', 'lisi1');
insert into `user`(id, username, password, mobile, email,sex, nickname) VALUES(11, 'lisi11', '123456', '13918891675','[email protected]', 'm', 'lisi1');
insert into `user`(id, username, password, mobile, email,sex, nickname) VALUES(12, 'lisi12', '123456', '13918891675','[email protected]', 'm', 'lisi1');
insert into `user`(id, username, password, mobile, email,sex, nickname) VALUES(13, 'lisi13', '123456', '13918891675','[email protected]', 'm', 'lisi1');
insert into `user`(id, username, password, mobile, email,sex, nickname) VALUES(14, 'lisi14', '123456', '13918891675','[email protected]', 'm', 'lisi1');
4.2. 用mybatis generator自動生成文件
參考我的另一篇blog,Springboot項目搭建:整合Mybatis-generator
4.3. 寫dao和service,controller,mapper
mapper增加了幾個方法
@Select("Select * from user")
List<User> selectAll();
@Select("Select * from user where username = #{username} and password = #{password}")
User selectByUsernamePass(@Param("username") String username, @Param("password") String password);
@Select("Select * from user where username = #{username}")
User selectByUsername(@Param("username") String username);
dao和service都是正常調用,下面是controller
package com.zb.controller;
import com.github.pagehelper.PageInfo;
import com.zb.model.User;
import com.zb.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/user")
@ResponseBody
public User getUserById(int id){
User user = userService.selectByPrimaryKey(id);
return user;
}
@RequestMapping("/userlist")
public String getUserList(Model model, PageInfo pageInfo){
int pageNum = (pageInfo.getPageNum() == 0)? 1 : pageInfo.getPageNum();
int pageSize = (pageInfo.getPageSize() == 0)? 10 : pageInfo.getPageSize();
PageInfo<User> result = userService.selectAll(pageNum, pageSize);
model.addAttribute("users", result.getList());
model.addAttribute("pageInfo", result);
return "userlist";
}
@RequestMapping("/userdelete")
public String userdelete(int id){
userService.deleteByPrimaryKey(id);
return "redirect:/userlist";
}
@RequestMapping("/useredit")
public String useredit(int id, Model model){
User user = userService.selectByPrimaryKey(id);
model.addAttribute("user", user);
return "useredit";
}
@RequestMapping(value = "/userupdateoradd", method = RequestMethod.POST)
public String userUpdateOrAdd(User user){
if(user.getId() == 0){
userService.insertSelective(user);
} else {
userService.updateByPrimaryKeySelective(user);
}
return "redirect:/userlist";
}
}
頁面userlist.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8" />
<title>用戶管理</title>
<link href="/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<div>
<nav class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div>
<ul class="nav navbar-nav" >
<li><a href="/userlist">用戶管理</a></li>
<li><a href="#">書籍管理</a></li>
</ul>
</div>
</div>
</nav>
</div>
<div>
<h2>用戶管理</h2>
<table width="100%" border="0" cellpadding="0" cellspacing="0" class="table_list">
<thead>
<tr>
<th width="20%">編號</th>
<th width="20%">用戶名</th>
<th width="20%">電子郵箱</th>
<th width="20%">手機</th>
<th width="20%">操作</th>
</tr>
</thead>
<tbody>
<tr th:each="user:${users}">
<td height="40px"><a th:text="${user.id}" data-toggle="modal" data-target="#myModal" onclick="values(this)"></a></td>
<td th:text="${user.username}"></td>
<td th:text="${user.email}"></td>
<td th:text="${user.mobile}"></td>
<td><a href="#" class="delete_a" th:value="${user.id}">刪除</a></td>
</tr>
</tbody>
</table>
</div>
</div>
<script src="/js/jquery-2.2.1.min.js"></script>
<script src="/js/bootstrap.min.js"></script>
</body>
</html>
在Application.java上加上註解掃描
@ComponentScan(basePackages = {"com.zb"})
@MapperScan("com.zb.mapper")
加上分頁工具
分頁-service層
@Override
public PageInfo<User> selectAll(int pageNum, int pageSize) {
PageHelper.startPage(pageNum, pageSize);
List<User> users = userDao.selectAll();
PageInfo<User> pageInfo = new PageInfo<>(users);
return pageInfo;
}
分頁-controller層
public String getUserList(Model model, PageInfo pageInfo){
int pageNum = (pageInfo.getPageNum() == 0)? 1 : pageInfo.getPageNum();
int pageSize = (pageInfo.getPageSize() == 0)? 10 : pageInfo.getPageSize();
PageInfo<User> result = userService.selectAll(pageNum, pageSize);
model.addAttribute("users", result.getList());
model.addAttribute("pageInfo", result);
return "userlist";
}
頁面修改
<div id="example" style="text-align: center"> <ul id="pageLimit"></ul> </div>
<input type="hidden" id="pageNum" name="pageNum" th:value="${pageInfo.pageNum}" />
<input type="hidden" id="pages" name="pages" th:value="${pageInfo.pages}" />
<script src="/js/bootstrap-paginator.min.js"></script>
<script>
$('#pageLimit').bootstrapPaginator({
currentPage: $("#pageNum").val(),
totalPages: $("#pages").val(),
size: "normal",
bootstrapMajorVersion: 3,
alignment: "right",
numberOfPages: 5,
itemTexts: function (type, page, current) {
switch (type) {
case "first": return "首頁";
case "prev": return "上一頁";
case "next": return "下一頁";
case "last": return "末頁";
case "page": return page;
}
},
onPageClicked: function (event, originalEvent, type, page){//給每個頁眉綁定一個事件,其實就是ajax請求,其中page變量爲當前點擊的頁上的數字。
window.location.href = "userlist?pageNum=" + page;
}
});
$(function(){
$(".delete_a").click(function(){
var userId=$(this).attr("value");
if(confirm("確認刪除嗎?")){
window.location.href="/userdelete?id=" + userId;
return ;
}
});
});
</script>
此時目錄
此時重啓,輸入 http://localhost:8080/userlist
就會看到user列表,也可以分頁。
寫在最後,推薦參考blog
-
參考文章
-
SpringBoot佈道系列 | 目錄彙總 | 2019持續更新ing
-
比較好的springboot項目
- https://github.com/Foreveriss/SpringBoot/blob/master/microboot-activemq/src/main/java/cn/mldn/microboot/dao/IDeptDAO.java
- https://github.com/xiaojiang1230/demo2/blob/4b87e5506edd69f19979a18d9a2597b99701f99f/src/main/java/com/example/demo/Demo2Application.java
- https://github.com/Foreveriss/SpringBoot/blob/0e66e801f4191e016f653602d3ef1184baa50adc/microboot-activemq/src/main/java/cn/mldn/microboot/service/IDeptService.java
-
springboot 整合mybatis實現動態sql
-
springboot 整合log4j
-
關於spring boot自動注入出現Consider defining a bean of type ‘xxx’ in your configuration問題解決方案