springBoot03- springboot+jpa+thymeleaf增刪改查

參考http://www.mooooc.com/springboot/2017/09/23/spring-boot-jpa-thymeleaf-curd.html css

數據庫:html

CREATE TABLE `user` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `username` varchar(50) DEFAULT NULL,
  `password` varchar(50) NOT NULL,
  `age` int(10) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4

項目結構:前端

1.模版下載:java

http://start.spring.io/    在搜索框分別輸入Web  Thymeleaf JPA MySQL, 下載的模版工程中就自動有這些依賴配置了mysql

1.pom文件:git

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

    <groupId>com.lch</groupId>
    <artifactId>springboot03</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>springboot03</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <!--本機安裝的是jdk1.7,此處改成1.7,project Structure裏的project SDK改成jdk1.7安裝地址,
        settings下Java Compile下的target bytecode version也改成1.7,而後再更新maven項目便可
        view下tool windows,選擇maven projects,在打開的maven 窗口點擊刷新便可 -->
        <java.version>1.7</java.version>
    </properties>

    <dependencies>
        <!--下載模版項目時,選上Web Thymeleaf JPA MySQL,此處就自動有這些依賴配置了-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>


</project>

2. github

啓動類添加Servlet的支持:繼承SpringBootServletInitializer
package com.lch.springboot03;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;

@SpringBootApplication
public class Springboot03Application extends SpringBootServletInitializer{

    public static void main(String[] args) {
        SpringApplication.run(Springboot03Application.class, args);
    }

    /**
     * 啓動類添加Servlet的支持:繼承SpringBootServletInitializer
     * alt+ Insert 選擇對configure()方法進行重寫
     * @return
     */
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        return builder.sources(Springboot03Application.class);
    }
}

 

3.實體類 及 數據訪問層接口定義web

user.java 
spring

 1 package com.lch.springboot03.domain;
 2 
 3 import javax.persistence.*;
 4 
 5 /**
 6  * 實體類映射數據庫表
 7  * 使用spring data jpa開發的時候,會將實體類中的成員變量與表中的字段一一對應,
 8  * 當咱們在實體類中加上一個不與數據庫表一一對應的成員變量的時候,此時咱們只要在
 9  * 這個成員變量上加上註解@Transient
10  */
11 @Entity
12 public class User {
13     @Id
14     @GeneratedValue(strategy = GenerationType.IDENTITY)
15     private Long id;
16 
17     @Column(nullable = false)
18     private String password;
19     //name="username" 設置userName屬性映射到數據庫的username字段,而不是默認的user_name
20     @Column(name = "username", nullable = true, unique = true)
21     private String userName;
22 
23     @Column(nullable = true, unique = true)
24     private int age;
25 
26     public Long getId() {
27         return id;
28     }
29 
30     public void setId(Long id) {
31         this.id = id;
32     }
33 
34     public String getPassword() {
35         return password;
36     }
37 
38     public void setPassword(String password) {
39         this.password = password;
40     }
41 
42     public String getUserName() {
43         return userName;
44     }
45 
46     public void setUserName(String userName) {
47         this.userName = userName;
48     }
49 
50     public int getAge() {
51         return age;
52     }
53 
54     public void setAge(int age) {
55         this.age = age;
56     }
57 
58 
59 }
View Code

UserRepository
1 package com.lch.springboot03.repository;
2 
3 import com.lch.springboot03.domain.User;
4 import org.springframework.data.jpa.repository.JpaRepository;
5 public interface UserRepository extends JpaRepository<User,Long>{
6 
7     User findById(long id);
8     void deleteById(Long id);
9 }

4. service層sql

 1 package com.lch.springboot03.service;
 2 
 3 import com.lch.springboot03.domain.User;
 4 
 5 import java.util.List;
 6 
 7 public interface UserService {
 8     /**
 9      * 獲取全部
10      *
11      * @return
12      */
13     public List<User> getUserList();
14 
15     /**
16      * 根據id獲取
17      *
18      * @param id
19      * @return
20      */
21     public User findUserById(long id);
22 
23     /**
24      * 新增
25      *
26      * @param user
27      */
28     public void save(User user);
29 
30     /**
31      * 修改
32      *
33      * @param user
34      */
35     public void edit(User user);
36 
37     /**
38      * 刪除
39      *
40      * @param id
41      */
42     public void delete(long id);
43 
44 
45 }
 1 package com.lch.springboot03.service;
 2 
 3 import com.lch.springboot03.domain.User;
 4 import com.lch.springboot03.repository.UserRepository;
 5 import org.springframework.beans.factory.annotation.Autowired;
 6 import org.springframework.stereotype.Service;
 7 
 8 import java.util.List;
 9 @Service
10 public class UserServiceImpl implements UserService {
11 
12     @Autowired
13     private UserRepository userRepository;
14     @Override
15     public List<User> getUserList() {
16         return userRepository.findAll();
17     }
18 
19     @Override
20     public User findUserById(long id) {
21         return userRepository.findById(id);
22     }
23 
24     @Override
25     public void save(User user) {
26         userRepository.save(user);
27     }
28 
29     @Override
30     public void edit(User user) {
31         userRepository.save(user);
32     }
33 
34     @Override
35     public void delete(long id) {
36         userRepository.deleteById(id);
37     }
38 
39 
40 }

5.controller

 1 package com.lch.springboot03.controller;
 2 
 3 import com.lch.springboot03.domain.User;
 4 import com.lch.springboot03.service.UserService;
 5 import org.springframework.stereotype.Controller;
 6 import org.springframework.ui.Model;
 7 import org.springframework.web.bind.annotation.RequestMapping;
 8 
 9 import javax.annotation.Resource;
10 import java.util.List;
11 
12 @Controller
13 public class UserController {
14     @Resource
15     private UserService userService;
16     @RequestMapping("/")
17     public String index(){
18         return "redirect:/list"; //重定向到 /list
19     }
20 
21     @RequestMapping("/list")
22     public String lsit(Model model){
23         List<User> users = userService.getUserList();
24         model.addAttribute("users",users);
25         return "user/list"; // 跳轉到springboot03\src\main\resources\templates\user下的list.html
26     }
27 
28     @RequestMapping("/toAdd")
29     public String toadd(User user){
30         return "user/userAdd";//跳轉到userAdd.html
31     }
32 
33     @RequestMapping("/add")
34     public String add(User user){
35         userService.save(user);
36         return "redirect:/list";//添加完成,請求重定向到/list
37     }
38 
39     @RequestMapping("/toEdit")
40     public String toEdit(Model model,Long id){
41         User user = userService.findUserById(id);
42         model.addAttribute("user",user);
43         return "user/userEdit"; //跳轉到userEdit.html頁面
44     }
45     @RequestMapping("/edit")
46     public String edit(User user){
47         userService.edit(user);
48         return "redirect:/list";//獲取列表數據並顯示
49     }
50 
51     @RequestMapping("/delete")
52     public String edit(Long id){
53         userService.delete(id);
54         return "redirect:/list";
55     }
56 }

return "user/userEdit"; 表明會直接去 resources 目錄下找相關的文件。

6. 前端頁面:

在resources的statics目錄下,創建css文件夾,把bootstrap.css拷貝進去。在templates目錄下建user目錄,下面建list.html,userAdd.html ,userEdit.html ,與controller中定義的對應

lsit.html

 1 <!DOCTYPE html>
 2 <html lang="en" xmlns:th="http://www.thymeleaf.org">
 3 <head>
 4     <meta charset="UTF-8"/>
 5     <title>userList</title>
 6     <link rel="stylesheet" th:href="@{/css/bootstrap.css}"></link>
 7 </head>
 8 <body class="container">
 9 <br/>
10 <h1>用戶列表</h1>
11 <br/><br/>
12 <div class="with:80%">
13     <table class="table table-hover">
14         <thead>
15         <tr>
16             <th>#</th>
17             <th>User Name</th>
18             <th>Password</th>
19             <th>Age</th>
20             <th>Edit</th>
21             <th>Delete</th>
22         </tr>
23         </thead>
24         <tbody>
25         <tr  th:each="user : ${users}">
26             <th scope="row" th:text="${user.id}">1</th>
27             <td th:text="${user.userName}">neo</td>
28             <td th:text="${user.password}">Otto</td>
29             <td th:text="${user.age}">6</td>
30             <td><a th:href="@{/toEdit(id=${user.id})}">edit</a></td>
31             <td><a th:href="@{/delete(id=${user.id})}">delete</a></td>
32         </tr>
33         </tbody>
34     </table>
35 </div>
36 <div class="form-group">
37     <div class="col-sm-2 control-label">
38         <a href="/toAdd" th:href="@{/toAdd}" class="btn btn-info">add</a>
39     </div>
40 </div>
41 
42 </body>
43 </html>

userAdd.html 

 1 <!DOCTYPE html>
 2 <html lang="en" xmlns:th="http://www.thymeleaf.org">
 3 <head>
 4     <meta charset="UTF-8"/>
 5     <title>user</title>
 6     <link rel="stylesheet" th:href="@{/css/bootstrap.css}"></link>
 7 </head>
 8 <body class="container">
 9 <br/>
10 <h1>添加用戶</h1>
11 <br/><br/>
12 <div class="with:80%">
13     <form class="form-horizontal"   th:action="@{/add}"  method="post">
14         <div class="form-group">
15             <label for="userName" class="col-sm-2 control-label">userName</label>
16             <div class="col-sm-10">
17                 <input type="text" class="form-control" name="userName"  id="userName" placeholder="userName"/>
18             </div>
19         </div>
20         <div class="form-group">
21             <label for="password" class="col-sm-2 control-label" >Password</label>
22             <div class="col-sm-10">
23                 <input type="password" class="form-control" name="password" id="password" placeholder="Password"/>
24             </div>
25         </div>
26         <div class="form-group">
27             <label for="age" class="col-sm-2 control-label">age</label>
28             <div class="col-sm-10">
29                 <input type="text" class="form-control" name="age"  id="age" placeholder="age"/>
30             </div>
31         </div>
32         <div class="form-group">
33             <div class="col-sm-offset-2 col-sm-10">
34                 <input type="submit" value="Submit" class="btn btn-info" />
35                 &nbsp; &nbsp; &nbsp;
36                 <input type="reset" value="Reset" class="btn btn-info" />
37             </div>
38 
39         </div>
40     </form>
41 </div>
42 </body>
43 </html>

userEdit.html

 1 <!DOCTYPE html>
 2 <html lang="en" xmlns:th="http://www.thymeleaf.org">
 3 <head>
 4     <meta charset="UTF-8"/>
 5     <title>user</title>
 6     <link rel="stylesheet" th:href="@{/css/bootstrap.css}"></link>
 7 </head>
 8 <body class="container">
 9 <br/>
10 <h1>修改用戶</h1>
11 <br/><br/>
12 <div class="with:80%">
13     <form class="form-horizontal"   th:action="@{/edit}" th:object="${user}"  method="post">
14         <input type="hidden" name="id" th:value="*{id}" />
15         <div class="form-group">
16             <label for="userName" class="col-sm-2 control-label">userName</label>
17             <div class="col-sm-10">
18                 <input type="text" class="form-control" name="userName"  id="userName" th:value="*{userName}" placeholder="userName"/>
19             </div>
20         </div>
21         <div class="form-group">
22             <label for="password" class="col-sm-2 control-label" >Password</label>
23             <div class="col-sm-10">
24                 <input type="password" class="form-control" name="password" id="password"  th:value="*{password}" placeholder="Password"/>
25             </div>
26         </div>
27         <div class="form-group">
28             <label for="age" class="col-sm-2 control-label">age</label>
29             <div class="col-sm-10">
30                 <input type="text" class="form-control" name="age"  id="age" th:value="*{age}" placeholder="age"/>
31             </div>
32         </div>
33         <div class="form-group">
34             <div class="col-sm-offset-2 col-sm-10">
35                 <input type="submit" value="Submit" class="btn btn-info" />
36                 &nbsp; &nbsp; &nbsp;
37                 <a href="/toAdd" th:href="@{/list}" class="btn btn-info">Back</a>
38             </div>
39 
40         </div>
41     </form>
42 </div>
43 </body>
44 </html>

7.數據庫鏈接配置:

 1 spring.datasource.url=jdbc:mysql://127.0.0.1/test?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC&useSSL=true
 2 spring.datasource.username=root
 3 spring.datasource.password=root
 4 spring.datasource.driver-class-name=com.mysql.jdbc.Driver
 5 
 6 spring.jpa.properties.hibernate.hbm2ddl.auto=update
 7 spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
 8 spring.jpa.show-sql= true
 9 #關閉thymeleaf的緩存,否則在開發過程當中修改頁面不會馬上生效須要重啓,生產可配置爲true
10 spring.thymeleaf.cache=false

8. 啓動項目並訪問:http://localhost:8080/list

點擊add :

 

github 代碼地址:

https://github.com/liuch0228/springboot.git
相關文章
相關標籤/搜索