天天看點

從.Net到Java學習第六篇——SpringBoot+mongodb&Thymeleaf&模型驗證

SpringBoot系列目錄

SpringBoot整合mongodb

  MongoDB 是一個介于關系資料庫和非關系資料庫之間的産品,是非關系資料庫當中功能最豐富,最像關系資料庫的。

如果你沒用過MongoDB,可以先去看下我的文章:https://www.cnblogs.com/jiekzou/category/851166.html

  接上一篇,修改pom.xml,添加mongodb的依賴

<!--mongodb-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>      

  添加mongodb資料庫連接配接,修改application.yml

spring:
  profiles:
    active: dev
  #  mongodb
  data:
    mongodb:
      database: test
      port: 27017
      host: 192.168.1.18      

 修改原來的Person實體類

public class Person {
    @Id
    private Long id;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    private String name;
    private String sex;

    public Person() {
    }

    public Person(Long id,String name, String sex) {
        this.id=id;
        this.name = name;
        this.sex = sex;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }      

建立包repository,然後在包下建立一個資料操作層接口PersonRepository,繼承MongoRepository,代碼如下:

public interface PersonRepository extends MongoRepository<Person,Long> {
}      

建立一個controller類PersonController進行增删改查測試

@RestController
public class PersonController {
    @Autowired
    private PersonRepository userRepository;

    @GetMapping("save")
    public String save() {
        Person userInfo = new Person(System.currentTimeMillis(),"李尋歡","男");
        userRepository.save(userInfo);
        return "success";
    }

    @GetMapping("getUserList")
    public List<Person> getUserList() {
        List<Person> userInfoList = userRepository.findAll();
        return userInfoList;
    }

    @GetMapping("delete")
    public String delete(Long id) {
        userRepository.delete(id);
        return "success";
    }

    @GetMapping("update")
    public String update(Long id, String username, String password) {
        Person userInfo = new Person(id, username, password);
        userRepository.save(userInfo);
        return "success";
    }
}      

通路http://localhost:8083/boot/save,刷幾遍,添加幾條資料

然後再通路http://localhost:8083/boot/getUserList檢視資料

從.Net到Java學習第六篇——SpringBoot+mongodb&amp;Thymeleaf&amp;模型驗證

當然,我們也可以使用可視化的mongodb管理工具去檢視,這裡我使用的是robo3t

從.Net到Java學習第六篇——SpringBoot+mongodb&amp;Thymeleaf&amp;模型驗證

在配置了mysql、mongodb等資料庫連接配接之後我們發現,基本上我們都離不開如下幾個步驟:

  1. 加入對應依賴
  2. 配置檔案配置對應資料庫資訊
  3. 資料操作層繼承想要的repository

SpringBoot引用Thymeleaf

Thymeleaf就是一個模闆引擎和.net的razor一樣。Spring boot 推薦用來代替jsp。

Thymeleaf的優點

  •     Thymeleaf 在有網絡和無網絡的環境下皆可運作,即它可以讓美工在浏覽器檢視頁面的靜态效果,也可以讓程式員在伺服器檢視帶資料的動态頁面效果。(當有資料傳回到頁面時,Thymeleaf 标簽會動态地替換掉靜态内容,使頁面動态顯示。)
  •     Thymeleaf 開箱即用的特性。(它提供标準和spring标準兩種方言,可以直接套用模闆實作JSTL、 OGNL表達式效果。)
  •     Thymeleaf 提供spring标準方言和一個與 SpringMVC 完美內建的可選子產品,可以快速的實作表單綁定、屬性編輯器、國際化等功能。

另外,Thymeleaf是一個XML/XHTML/HTML5模闆引擎,可用于Web與非Web環境中的應用開發。它是一個開源的Java庫,基于Apache License 2.0許可,由Daniel Fernández建立,該作者還是Java加密庫Jasypt的作者。

由于Thymeleaf使用了XML DOM解析器,是以它并不适合于處理大規模的XML檔案。也就是說它的性能是有一定問題的,如果檔案較大的情況下。

關于Thymeleaf的文法可以參考官網:https://www.thymeleaf.org/documentation.html

spring boot(四):thymeleaf使用詳解

SpringBoot引用Thymeleaf依賴

修改pom.xml,添加如下依賴

<!--thymeleaf-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>      

這裡有個坑,預設情況下hymeleaf中所有的标簽都必須成對出現,否則IDEA運作時就會報錯:" 必須由比對的結束标記終止..“。

據說spring boot 2.0已結修複了這個标簽的問題,但是我這裡目前用的版本是低于2.0的,是以需要額外處理。

繼續添加依賴

<dependency>
            <groupId>net.sourceforge.nekohtml</groupId>
            <artifactId>nekohtml</artifactId>
            <version>1.9.22</version>
        </dependency>      

然後修改application.yml中的配置,

spring:
  profiles:
    active: dev
  thymeleaf:
    mode: LEGACYHTML5      

建立一個控制器類來做測試,AreaPageController,

@Controller
public class AreaPageController{
    @Autowired
    private AreaService areaService;

    @GetMapping("/addArea")
    public String addArea(Model model) {
        model.addAttribute("area", new Area());
        return "addArea";
    }
    @RequestMapping(value = "/addArea",method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String addArea(@Valid @ModelAttribute Area area, BindingResult bindingResult){
        if (bindingResult.hasErrors()) {
            return "addArea";
        }else{
            Map<String,Object> modelMap= new HashMap<String,Object>() ;
            modelMap.put("success",areaService.addArea(area));
            return "result";
        }
    }
}      

修改之前的Area實體類,這東西就跟.net mvc 裡面的模型驗證一樣

package com.yujie.model;

import org.hibernate.validator.constraints.NotEmpty;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.util.Date;

public class Area {
    private Integer areaId;
    @NotEmpty
    @Size(min=2, max=30)
    private String areaName;
    @NotNull
    @Min(1)
    @Max(200)
    private Integer priority;
    private Date createTime;
    private Date lastEditTime;
  ......
}      

templates目錄是存放html檔案的,在templates目錄下面建立一個html檔案addArea.html,這個就相當于.net mvc中的razor視圖。

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"><!--引入thymeleaf-->
<head>
    <meta charset="UTF-8" />
    <title>添加區域</title></head>
<link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<body>
    <h2 style="color:green;text-align: center;">添加區域</h2>
    <form class="form-horizontal" role="form" action="#" th:action="@{/addArea}" th:object="${area}" method="post">
        <div class="form-group"><label for="name" class="col-sm-2 control-label">區域名稱:</label>
            <div class="col-sm-8"><input type="text" th:field="*{areaName}" class="form-control" id="areaName"
                                          placeholder="輸入區域名稱"></div>
            <label class="col-sm-2" style="color:red" th:if="${#fields.hasErrors('areaName')}" th:errors="*{areaName}">區域名稱錯誤</label></div>
        <div class="form-group"><label for="priority" class="col-sm-2 control-label">優先級</label>
            <div class="col-sm-8"><input type="text" th:field="*{priority}" class="form-control" id="priority"
                                          placeholder="輸入優先級"></div>
            <label class="col-sm-2" style="color:red" th:if="${#fields.hasErrors('priority')}" th:errors="*{priority}">優先級錯誤</label></div>
        <div class="form-group">
            <div class="col-sm-12" style="text-align: center">
                <button type="submit" class="btn btn-primary" id="btn">Submit</button>
                <input type="reset" class="btn btn-warning" value="Reset"/></div>
        </div>
    </form>
</body>
</html>      

運作結果如下:

從.Net到Java學習第六篇——SpringBoot+mongodb&amp;Thymeleaf&amp;模型驗證

其它學習資料:Spring Web MVC架構(十二) 使用Thymeleaf

部落格位址: http://www.cnblogs.com/jiekzou/
部落格版權:

本文以學習、研究和分享為主,歡迎轉載,但必須在文章頁面明顯位置給出原文連接配接。

如果文中有不妥或者錯誤的地方還望高手的你指出,以免誤人子弟。如果覺得本文對你有所幫助不如【推薦】一下!如果你有更好的建議,不如留言一起讨論,共同進步!

再次感謝您耐心的讀完本篇文章。

其它:

.net-QQ群4:612347965

java-QQ群:805741535

H5-QQ群:773766020

我的拙作《ASP.NET MVC企業級實戰》《H5+移動應用實戰開發》

《Vue.js 2.x實踐指南》

《JavaScript實用教程 》

《Node+MongoDB+React 項目實戰開發》

已經出版,希望大家多多支援!

從.Net到Java學習第六篇——SpringBoot+mongodb&amp;Thymeleaf&amp;模型驗證