# JAVA SPRING開發筆記1 [名詞解析](https://hackmd.io/PBmL34B8QVOPgD2eMfcgxg) [toc] 由於上學不會學到spring所以這種東西只能自學 經由[codejava](https://www.youtube.com/watch?v=QloyS2dt9T4)所著的spring crud教學而成的筆記 由於我們要做crud 就要先來說說spring crud又叫增刪改查(Create Delete Read Update) 而我們所做的是最簡單的 沒有登入系統 沒有CSS 沒有JS 很單純的商品管理系統 可以CRUD你的產品並加入SQL中 而在中間我可以學到 1.spring jpa要怎麼設定和mysql的連線,要在之中加入什麼 2.怎麼使用介面,什麼是MVC 3.ThymeLeaf模板要怎麼用,怎麼用它方便你把資料庫的東西傳到後端再往前面的HTML送 4.spring boot 專案的基礎設定,尤其是如何用IDE將會用到的lib放入pom.xml設定檔中 ![image](https://hackmd.io/_uploads/B1XsyShB6.png) 介面層(Controller) 接收前端請求(處理網址) 業務邏輯層(Service):根據請求做資料處理或是處理從DAO回來的資料。 資料訪問層(Dao):對資料庫做增修查改等操作。 # 1.MySQL建檔 ![image](https://hackmd.io/_uploads/rJ9x1S3ra.png) 我們先簡單的創建一個可以存各種品牌的清單 此時我們的product會長這樣 ![image](https://hackmd.io/_uploads/HJT8kHnr6.png) 沒有任何東西空的 我們就完成了MySQL的建置 # 2.Spring.io的快速建檔 接下來我們利用spring.io的快速建置spring [https://start.spring.io](https://start.spring.io) ![image](https://hackmd.io/_uploads/rkze-S2S6.png) 將我們需要的東西依序填入並generate ![image](https://hackmd.io/_uploads/rkX6er2B6.png) 他會給我們一個壓縮檔 ![image](https://hackmd.io/_uploads/HkiXZShHa.png) 我們將這壓縮檔匯入IDE中 ![image](https://hackmd.io/_uploads/S1yKbSnB6.png) # 3.Spring設置 一開始會內建這個啟動程式 我們不用去配置什麼 ![image](https://hackmd.io/_uploads/B198fH3BT.png) ### application 第二個就是application.properties的配置 application.properties是整個spring的配置文件 要修改任何東西都在這 ``` spring.jpa.hibernate.ddl-auto=none spring.datasource.url=jdbc:mysql://localhost:3306/sales spring.datasource.username=root spring.datasource.password=123456 logging.level.root=WARN ``` 包含我們的database來源 端口 帳號密碼 ### model ``` package spring.practice; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id; @Entity public class Product { private Long id; private String name; private String brand; private String madein; private float price; protected Product() { } @Id @GeneratedValue(strategy = GenerationType.IDENTITY) public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getBrand() { return brand; } public void setBrand(String brand) { this.brand = brand; } public String getMadein() { return madein; } public void setMadein(String madein) { this.madein = madein; } public float getPrice() { return price; } public void setPrice(float price) { this.price = price; } } ``` ### Repository 繼承JpaRepository 重點都會放在下一個service ``` package spring.practice; import org.springframework.data.jpa.repository.JpaRepository; public interface ProductRepository extends JpaRepository<Product, Long>{ } ``` ### Service 我們ProductRepositiry repo 就可以利用repo.XXXX來call其他函數 ``` package spring.practice; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class ProductService { @Autowired private ProductRepository repo; public List<Product> listAll() { return repo.findAll(); } public void save(Product product) { repo.save(product); } public Product get(Long id) { return repo.findById(id).get(); } public void delete(Long id) { repo.deleteById(id); } } ``` ### Controller 所以spring的控制頁面都在這 分別寫好CRUD 並給他們一個對應的url ``` package spring.practice; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; @Controller public class AppController { @Autowired private ProductService service; @RequestMapping("/") public String viewHomePage(Model model) { List<Product> listProducts = service.listAll(); model.addAttribute("listProducts", listProducts); return "index"; } @RequestMapping("/new") public String showNewProductPage(Model model) { Product product = new Product(); model.addAttribute("product", product); return "new_product"; } @RequestMapping(value = "/save", method = RequestMethod.POST) public String saveProduct(@ModelAttribute("product") Product product) { service.save(product); return "redirect:/"; } @RequestMapping("/edit/{id}") public ModelAndView showEditProductPage(@PathVariable(name = "id") Long id) { ModelAndView mav = new ModelAndView("edit_product"); Product product = service.get(id); mav.addObject("product",product); return mav; } @RequestMapping("/delete/{id}") public String deleteProduct(@PathVariable(name = "id") Long id) { service.delete(id); return "redirect:/"; } } ``` ### Exception # 4.html 上面我們已經將java spring設置好了 接下來只要配置好html就好 我們將html放入 ![image](https://hackmd.io/_uploads/B1SaQIhSa.png) ### index ``` <!DOCTYPE html> <html xmlns:th="http://www.thymeLeaf.org"> <head> <meta charset="BIG5"> <title>Product Manager</title> </head> <body> <div align="center"> <h1>Product Manager</h1> <a href="/new">Create New Product</a> <table border="1" cellpadding="10"> <thead> <tr> <th>Product ID</th> <th>Name</th> <th>Brand</th> <th>Made In</th> <th>Price</th> <th>Actions</th> </tr> </thead> <tbody> <tr th:each="product : ${listProducts}"> <td th:text="${product.id}">Product ID</td> <td th:text="${product.name}">Name</td> <td th:text="${product.brand}">Brand</td> <td th:text="${product.madein}">Made In</td> <td th:text="${product.price}">Price</td> <td> <a th:href="@{'/edit/' + ${product.id}}">Edit</a> &nbsp;&nbsp;&nbsp;&nbsp; <a th:href="@{'/delete/' + ${product.id}}">Delete</a> </td> </tr> </tbody> </table> </div> </body> </html> ``` ### new_product ``` <!DOCTYPE html> <html xmlns:th="http://www.thymeLeaf.org"> <head> <meta charset="BIG5"> <title>Create New Product</title> </head> <body> <div align="center"> <h1>Create New Product</h1> <br /> <form action="#" th:action="@{/save}" th:object="${product}"method="post"> <table border="0" cellpadding="10"> <tr> <td>Product Name:</td> <td><input type="text" th:field="*{name}" /></td> </tr> <tr> <td>Brand:</td> <td><input type="text" th:field="*{brand}" /></td> </tr> <tr> <td>Made In:</td> <td><input type="text" th:field="*{madein}" /></td> </tr> <tr> <td>Price:</td> <td><input type="text" th:field="*{price}" /></td> </tr> <tr> <td colspan="2"><button type="submit">Save</button> </td> </tr> </table> </form> </div> </body> </html> ``` ### edit_product ``` <!DOCTYPE html> <html xmlns:th="http://www.thymeLeaf.org"> <head> <meta charset="BIG5"> <title>Edit Product</title> </head> <body> <div align="center"> <h1>Edit Product</h1> <br /> <form action="#" th:action="@{/save}" th:object="${product}"method="post"> <table border="0" cellpadding="10"> <tr> <td>Product ID:</td> <td><input type="text" th:field="*{id}" readonly="readonly" /></td> </tr> <tr> <td>Product Name:</td> <td><input type="text" th:field="*{name}" /></td> </tr> <tr> <td>Brand:</td> <td><input type="text" th:field="*{brand}" /></td> </tr> <tr> <td>Made In:</td> <td><input type="text" th:field="*{madein}" /></td> </tr> <tr> <td>Price:</td> <td><input type="text" th:field="*{price}" /></td> </tr> <tr> <td colspan="2"><button type="submit">Save</button> </td> </tr> </table> </form> </div> </body> </html> ``` # 5. 結果 ![image](https://hackmd.io/_uploads/HJSTBUhBT.png) 加入新的product ![image](https://hackmd.io/_uploads/rydCSLhB6.png) ![image](https://hackmd.io/_uploads/BkQ1UI3Ba.png) ![image](https://hackmd.io/_uploads/SyygI82Bp.png) 反映在sql以及網頁上 ![image](https://hackmd.io/_uploads/HyYCKU3r6.png) ![image](https://hackmd.io/_uploads/BkWJ9LnHp.png) 修改後 ![image](https://hackmd.io/_uploads/SJm4qL2ST.png) ![image](https://hackmd.io/_uploads/ryBlc83S6.png) 將她刪除後