thymeleaf springboot CRUD (新手向)
前言
我是以我原來mybatis+druid+mysql做CRUD為基礎http://www.reibang.com/p/4b285b5b34f8棘劣,主要借鑒了https://blog.csdn.net/zhuyu19911016520/article/details/81537154俏让。這個網(wǎng)址的沒做分頁呈础,我的做了能在我的程序上運行的分頁處理以及一些優(yōu)化舆驶。其中而钞,包括顯示上一頁與下一頁(如果有的話)沙廉,當前是第幾頁以及總共有多少頁。在刪除時不會刪了最后一頁的最后一個撬陵,直接跳到首頁(這是不知為何的機制所致)珊皿,而是對使用者友好的刪除后還在當前頁面(如果當前頁面仍然有數(shù)據(jù))蟋定。由于剛接觸远寸,所以在對于工具所提供的接口只會使用,背后的機制是不了解的≡钪ィ總之郑原,網(wǎng)上找的代碼大概意思能看懂,具體代碼層面的工作流程需要通過修復一個一個bug夜涕,以及加些新功能或者優(yōu)化一起學習犯犁。
放一下thymeleaf官網(wǎng) https://www.thymeleaf.org/。如果英語差钠乏,可以看菜鳥教程栖秕。
項目目的
前后端共同實現(xiàn)mysql分頁增刪改查
文件結構
上代碼
pom.xml
<?xmlversion="1.0"encoding="UTF-8"?>
<projectxmlns="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 https://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.1.RELEASE</version>
<relativePath/><!--lookupparentfromrepository-->
</parent>
<groupId>com.vue</groupId>
<artifactId>mybatis_druid_mysql</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>mybatis_druid_mysql</name>
<description>mybatis_druid_mysql</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
</dependency>
<!--web依賴春塌,包含servlet,內(nèi)置tomcat等-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--mysql依賴-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!--mybatis依賴-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<!--druid依賴包晓避,配合springBoot項目使用-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.14</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
<!--<version>2.3.4.RELEASE</version>-->
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Controller
importcom.mybatis_druid_mysql.demo.Entity.Customer;
importcom.mybatis_druid_mysql.demo.Service.Service;
importorg.springframework.beans.factory.annotation.Autowired;
importorg.springframework.data.domain.Page;
importorg.springframework.ui.ModelMap;
importorg.springframework.web.bind.annotation.ModelAttribute;
importorg.springframework.web.bind.annotation.RequestMapping;
importorg.springframework.web.bind.annotation.RequestParam;
importjava.util.Iterator;
@org.springframework.stereotype.Controller
@RequestMapping("customers")
publicclassController{
@Autowired
privateServiceservice;
@RequestMapping("edit")
publicStringedit(ModelMapmap,@RequestParam(value="pageNum",defaultValue="0")intpageNum,@RequestParam(value="pageSize",defaultValue="2")intpageSize,@RequestParam(defaultValue="0")intid){
//isAdd : 向前端頁面返回一個是新增與編輯的標識
if(id>0){
map.addAttribute("isAdd",0);
map.addAttribute("customer",service.getById(id));
map.addAttribute("pageNum",pageNum);
}else{
map.addAttribute("isAdd",1);
map.addAttribute("customer",newCustomer());
map.addAttribute("pageNum",pageNum);
? ? ?? }
return"customer/edit";
?? }
@RequestMapping("goingToDel")
publicStringgoingToDel(ModelMapmap,@RequestParam(value="pageNum",defaultValue="0")intpageNum,@RequestParam(value="pageSize",defaultValue="2")intpageSize,@RequestParam(value="id")intid){
map.addAttribute("customer",service.getById(id));
map.addAttribute("pageNum",pageNum);
return"customer/goingToDel";
?? }
@RequestMapping("list")
publicStringlist(ModelMapmap,@RequestParam(value="pageNum",defaultValue="0")intpageNum,@RequestParam(value="pageSize",defaultValue="2")intpageSize) {
System.out.println("============================");
Page<Customer>customers=service.getUserList(pageNum,pageSize);
System.out.println("總頁數(shù)"+customers.getTotalPages());
System.out.println("當前頁是:"+pageNum);
System.out.println("分頁數(shù)據(jù):");
Iterator<Customer>u=customers.iterator();
while(u.hasNext()){
System.out.println(u.next().toString());
? ? ?? }
map.addAttribute("customers",customers);
map.addAttribute("pageNum",pageNum);
return"customer/list";
?? }
//新增和編輯
@RequestMapping("save")
publicStringsave(ModelMapmap,@RequestParam(value="pageNum",defaultValue="0")intpageNum,@RequestParam(value="pageSize",defaultValue="2")intpageSize,@ModelAttributeCustomercustomer){
if(customer==null){
return"customer/list";
? ? ?? }
if(customer.getId()!=null&&customer.getId()>0){
service.edit(customer);
}else{
service.add(customer);
? ? ?? }
Page<Customer>customers=service.getUserList(pageNum,pageSize);
map.addAttribute("customers",customers);
map.addAttribute("pageNum",pageNum);
return"customer/list";
?? }
@RequestMapping("del")
publicStringdel(ModelMapmap,@RequestParam(value="pageNum",defaultValue="0")intpageNum,@RequestParam(value="pageSize",defaultValue="2")intpageSize,@ModelAttributeCustomercustomer){
if(customer==null){
return"customer/list";
? ? ?? }
service.delete(customer.getId());
Page<Customer>customers=service.getUserList(pageNum,pageSize);
Iterator<Customer>u=customers.iterator();
map.addAttribute("customers",customers);
map.addAttribute("pageNum",pageNum);
System.out.println(pageNum);
if(u.hasNext()){
System.out.println("1");
return"redirect:list?pageNum="+pageNum;
? ? ?? }
elseif(customers.getTotalPages()!=0) {
pageNum--;
System.out.println("2");
return"redirect:list?pageNum="+pageNum;
? ? ?? }
else{
System.out.println("3");
return"redirect:list?pageNum=0";
? ? ?? }
?? }
}
ModelMap對象主要用于傳遞控制方法處理數(shù)據(jù)到結果頁面,也就是說我們把結果頁面上需要的數(shù)據(jù)放到ModelMap對象中即可只壳。通過以下方法向頁面?zhèn)鬟f參數(shù):
publicModelMapaddAttribute(StringattributeName,ObjectattributeValue){...}
publicModelMapaddAttribute(ObjectattributeValue){...}
publicModelMapaddAllAttributes(Collection<?>attributeValues) {...}
publicModelMapaddAllAttributes(Map<String,?>attributes){...}
thymeleaf配置
###ThymeLeaf??
spring.thymeleaf.mode=HTML5
#????????HTML,XMLTEXTJAVASCRIPT
spring.thymeleaf.encoding=UTF-8
#???????
spring.thymeleaf.content-type=text/html
#????,?????
spring.thymeleaf.cache=false
#?????false,?????????????
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.prefix= classpath:/templates/spring.thymeleaf.suffix= .html
設置了thymeleaf的尋址地址以及文件格式俏拱。
Controller中return "customer/list";就是在thymeleaf的尋址地址基礎上再尋址找到相應的頁面。
至于return "redirect:list?pageNum=0"; 這是個重定位吼句。相當于調(diào)用Controller方法 http://127.0.0.1:8080/customers/list?pageNum=0
edit.html
<!DOCTYPEhtml>
<htmllang="en">
<head>
<metacharset="UTF-8"/>
<title>新增锅必、編輯客戶</title>
</head>
<body>
<formth:action="@{/customers/save}"method="post">
<!--//新增時不存在-->
<divth:if="${isAdd} == 0">
<labelstyle="color: red">id</label>
<inputtype="text"name="id"readonly="readonly"th:field="${customer.id}"style="background-color: red"/>
</div>
<div>
<label>name</label>
<inputtype="text"name="name"th:field="${customer.name}"/>
</div>
<div>
<label>age</label>
<inputtype="text"name="age"th:field="${customer.age}"/>
</div>
<div>
<label>used</label>
<inputtype="text"name="used"th:field="${customer.used}"/>
</div>
<div>
<inputtype="submit"value="提交"/>
</div>
<div>
<inputtype="button"value="返回"onclick="JavaScript:history.go(-1)"/>
</div>
<!--<div>-->
<!--<inputtype="button"value="刪除"onclick='remove(this)'/>-->
<!--</div>-->
</form>
</body>
</html>
goingToDel.html
<!DOCTYPEhtml>
<htmllang="en">
<head>
<metacharset="UTF-8"/>
<title>刪除客戶</title>
</head>
<body>
<formth:action="@{/customers/del(pageNum=${pageNum},id=${customer.id})}"method="post">
<div>
<label>id</label>
<inputtype="text"name="id"readonly="readonly"th:field="${customer.id}"/>
</div>
<div>
<label>name</label>
<inputtype="text"name="name"readonly="readonly"th:field="${customer.name}"/>
</div>
<div>
<label>age</label>
<inputtype="text"name="age"readonly="readonly"th:field="${customer.age}"/>
</div>
<div>
<label>used</label>
<inputtype="text"name="used"readonly="readonly"th:field="${customer.used}"/>
</div>
<div>
<inputtype="submit"value="確定刪除"/>
</div>
<div>
<inputtype="button"value="返回"onclick="JavaScript:history.go(-1)"/>
</div>
</form>
</body>
</html>
list.html
<!DOCTYPEhtml>
<htmllang="en"xmlns:th="http://www.thymeleaf.org">
<head>
<metacharset="UTF-8"/>
<title>客戶列表</title>
<style>
table{border-collapse:collapse;}
table,th,td{border:1pxsolidblack;padding:5px;text-align:center;}
</style>
<linkrel="stylesheet"th:href="@{/css/bootstrap.css}"/>
</head>
<bodyclass="container">
<br/>
<br/>
<ath:href="edit">新增用戶</a>
<br/>
<br/>
<table>
<thead>
<thwidth="20%">id</th>
<thwidth="20%">name</th>
<thwidth="20%">age</th>
<thwidth="20%">used</th>
<thwidth="20%">操作</th>
</thead>
<tbody>
<trth:each="customer : ${customers}">
<tdth:text="${customer.id}"></td>
<tdth:text="${customer.name}"></td>
<tdth:text="${customer.age}"></td>
<tdth:text="${customer.used}"></td>
<td>
<ath:href="@{/customers/edit(id=${customer.id})}">編輯</a>
<ath:href="@{/customers/goingToDel(pageNum=${pageNum},id=${customer.id})}">刪除</a>
</td>
</tr>
</tbody>
</table>
<divth:text="當前頁數(shù)"></div>
<divth:text="${pageNum}"></div>
<divclass="modal-footer no-margin-top">
<ulclass="pagination pull-right no-margin">
<!--首頁-->
<li>
<ath:href="'/customers/list?pageNum=0'">首頁</a>
</li>
<!--上一頁-->
<lith:if="${customers.hasPrevious()}">
<ath:href="'/customers/list?pageNum=' + ${customers.previousPageable().getPageNumber()}"th:text="上一頁"></a>
</li>
<!--中間頁-->
<lith:each="pageNum:${#numbers.sequence(0, customers.getTotalPages()-1)}">
<ath:href="'/customers/list?pageNum=' + ${pageNum}"th:text="${pageNum + 1}"th:style="'font-weight:bold;background: #6faed9;'"></a>
</li>
<!--下一頁-->
<lith:if="${customers.hasNext()}">
<ath:href="'/customers/list?pageNum=' + ${customers.nextPageable().getPageNumber()}"th:text="下一頁"></a>
</li>
<!--尾頁-->
<li>
<ath:href="'/customers/list?pageNum=' + ${customers.getTotalPages() - 1}">尾頁</a>
</li>
</ul>
</div>
</body>
</html>
UserRepositrory
publicinterfaceUserRepositoryextendsJpaRepository<Customer,Long>{
}
Service
@org.springframework.stereotype.Service
publicinterfaceService{
//新增
voidadd(Customercustomer);
//編輯
voidedit(Customercustomer);
//刪除
voiddelete(intid);
//獲取單個
CustomergetById(intid);
//獲取所有
List<Customer>listByAll();
Page<Customer>getUserList(intpageNum,intpageSize);
}
ServiceImpl
import com.mybatis_druid_mysql.demo.Entity.Customer;
import com.mybatis_druid_mysql.demo.Mapper.Mapper;
import com.mybatis_druid_mysql.demo.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import java.util.List;
@org.springframework.stereotype.Service
public class ServiceImpl implements Service {
@Autowired
private Mapper mapper;
@Autowired
private UserRepository userRepository;
@Override
public void add(Customer customer) {
mapper.insert(customer);
}
@Override
public void edit(Customer customer) {
mapper.updateByPrimaryKey(customer);
}
@Override
public void delete(int id) {
mapper.deleteByPrimaryKey(id);
}
@Override
public Customer getById(int id) {
return mapper.selectByPrimaryKey(id);
}
@Override
public List listByAll() {
return mapper.listByAll();
}
@Override
public Page getUserList(int pageNum, int pageSize) {
Pageable pageable = new PageRequest(pageNum, pageSize);
Page customers = userRepository.findAll(pageable);
return customers;
}
}