thymeleaf springboot CRUD (新手向)

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>&nbsp;&nbsp;

<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;

}

}

其余的都在http://www.reibang.com/p/4b285b5b34f8

?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末惕艳,一起剝皮案震驚了整個濱河市搞隐,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌远搪,老刑警劉巖劣纲,帶你破解...
    沈念sama閱讀 218,204評論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異谁鳍,居然都是意外死亡癞季,警方通過查閱死者的電腦和手機劫瞳,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,091評論 3 395
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來绷柒,“玉大人志于,你說我怎么就攤上這事》夏溃” “怎么了伺绽?”我有些...
    開封第一講書人閱讀 164,548評論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長嗜湃。 經(jīng)常有香客問我憔恳,道長,這世上最難降的妖魔是什么净蚤? 我笑而不...
    開封第一講書人閱讀 58,657評論 1 293
  • 正文 為了忘掉前任钥组,我火速辦了婚禮,結果婚禮上今瀑,老公的妹妹穿的比我還像新娘程梦。我一直安慰自己,他們只是感情好橘荠,可當我...
    茶點故事閱讀 67,689評論 6 392
  • 文/花漫 我一把揭開白布屿附。 她就那樣靜靜地躺著,像睡著了一般哥童。 火紅的嫁衣襯著肌膚如雪挺份。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,554評論 1 305
  • 那天贮懈,我揣著相機與錄音匀泊,去河邊找鬼。 笑死朵你,一個胖子當著我的面吹牛各聘,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播抡医,決...
    沈念sama閱讀 40,302評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼躲因,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了忌傻?” 一聲冷哼從身側響起大脉,我...
    開封第一講書人閱讀 39,216評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎水孩,沒想到半個月后镰矿,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,661評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡荷愕,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,851評論 3 336
  • 正文 我和宋清朗相戀三年衡怀,在試婚紗的時候發(fā)現(xiàn)自己被綠了棍矛。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,977評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡抛杨,死狀恐怖够委,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情怖现,我是刑警寧澤茁帽,帶...
    沈念sama閱讀 35,697評論 5 347
  • 正文 年R本政府宣布,位于F島的核電站屈嗤,受9級特大地震影響潘拨,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜饶号,卻給世界環(huán)境...
    茶點故事閱讀 41,306評論 3 330
  • 文/蒙蒙 一铁追、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧茫船,春花似錦琅束、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,898評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至然眼,卻和暖如春艾船,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背高每。 一陣腳步聲響...
    開封第一講書人閱讀 33,019評論 1 270
  • 我被黑心中介騙來泰國打工屿岂, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人觉义。 一個月前我還...
    沈念sama閱讀 48,138評論 3 370
  • 正文 我出身青樓雁社,卻偏偏與公主長得像,于是被迫代替她去往敵國和親晒骇。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 44,927評論 2 355

推薦閱讀更多精彩內(nèi)容