美文网首页
Spring Boot 整合 Thymeleaf

Spring Boot 整合 Thymeleaf

作者: 沧海一粟谦 | 来源:发表于2018-04-10 22:55 被阅读38次

    构建项目

    在pom.xml中添加依赖。

    <groupId>com.lcy</groupId>
    <artifactId>web</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.0.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>
        <java.version>1.8</java.version>
    </properties>
    <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-jpa</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-thymeleaf</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-tomcat</artifactId>
                <!--<scope>provided</scope>-->
            </dependency>
    

    在application.properties中添加配置

    spring.datasource.url=jdbc:mysql://127.0.0.1/spring?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC&useSSL=true
    spring.datasource.username=root
    spring.datasource.password=123456
    spring.datasource.driver-class-name=com.mysql.jdbc.Driver
    
    spring.jpa.properties.hibernate.hbm2ddl.auto=update
    spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
    spring.jpa.show-sql= true
    
    #thymeleaf start
    spring.thymeleaf.mode=HTML5
    spring.thymeleaf.encoding=UTF-8
    #开发时关闭缓存,不然没法看到实时页面,生产可配置为true
    spring.thymeleaf.cache=false
    #thymeleaf end
    

    在项目resources目录下有两个文件夹:static目录用于放置网站的静态内容如css、js、图片;templates目录用于放置项目使用的页面模板。

    实体类

    实体类映射数据库表

    @Entity
    public class User {
        @Id
        @GeneratedValue
        private long id;
        @Column(nullable = false, unique = true)
        private String userName;
        @Column(nullable = false)
        private String password;
        @Column(nullable = false)
        private int age;
    
        public long getId() {
            return id;
        }
        public User setId(long id) {
            this.id = id;
            return this;
        }
        ......
    

    创建UserRepository

    继承JpaRepository类会自动实现很多内置的方法,包括增删改查。也可以根据方法名来自动生成相关sql。

    public interface UserRepository extends JpaRepository<User, Long> {
        User findById(long id);
        void deleteById(Long id);   
     }
    

    业务层处理

    service调用jpa实现相关的增删改查,实际项目中service层处理具体的业务代码。

    @Service
    public class UserServiceImpl implements UserService{
    
        @Autowired
        private UserRepository userRepository;
    
        @Override
        public List<User> getUserList() {
            return userRepository.findAll();
        }
    
        @Override
        public User findUserById(long id) {
            return userRepository.findById(id);
        }
    
        @Override
        public void save(User user) {
            userRepository.save(user);
        }
    
        @Override
        public void delete(long id) {
            userRepository.delete(findUserById(id));
        }
    }
    

    Controller负责接收请求,处理完后将页面内容返回给前端。

    @Controller
    public class UserController {
    
        @Resource
        UserService userService;
    
        @RequestMapping("/")
        public String index() {
            return "redirect:/list";
        }
    
        @RequestMapping("/list")
        public String list(Model model) {
            List<User> users=userService.getUserList();
            model.addAttribute("users", users);
            return "user/list";
        }
    
        @RequestMapping("/toAdd")
        public String toAdd() {
            return "user/userAdd";
        }
    
        @RequestMapping("/add")
        public String add(User user) {
            userService.save(user);
            return "redirect:/list";
        }
    
        @RequestMapping("/toEdit")
        public String toEdit(Model model,Long id) {
            User user=userService.findUserById(id);
            model.addAttribute("user", user);
            return "user/userEdit";
        }
    
        @RequestMapping("/edit")
        public String edit(User user) {
            userService.save(user);
            return "redirect:/list";
        }
    
        @RequestMapping("/delete")
        public String delete(Long id) {
            userService.delete(id);
            return "redirect:/list";
        }
    }
    
    • return "user/userEdit"; 代表会直接去resources目录下找相关的文件。
    • return "redirect:/list"; 代表转发到对应的controller,这个示例就相当于删除内容之后自动调整到list请求,然后再输出到页面。

    前端页面

    <!DOCTYPE html>
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8"/>
        <title>userList</title>
        <link rel="stylesheet" th:href="@{/css/bootstrap.css}"></link>
    </head>
    <body class="container">
    <br/>
    <h1>用户列表</h1>
    <br/><br/>
    <div class="with:80%">
        <table class="table table-hover">
            <thead>
            <tr>
                <th>#</th>
                <th>User Name</th>
                <th>Password</th>
                <th>Age</th>
                <th>Edit</th>
                <th>Delete</th>
            </tr>
            </thead>
            <tbody>
            <tr  th:each="user : ${users}">
                <th scope="row" th:text="${user.id}">1</th>
                <td th:text="${user.userName}">neo</td>
                <td th:text="${user.passWord}">Otto</td>
                <td th:text="${user.age}">6</td>
                <td><a th:href="@{/toEdit(id=${user.id})}">edit</a></td>
                <td><a th:href="@{/delete(id=${user.id})}">delete</a></td>
            </tr>
            </tbody>
        </table>
    </div>
    <div class="form-group">
        <div class="col-sm-2 control-label">
            <a href="/toAdd" th:href="@{/toAdd}" class="btn btn-info">add</a>
        </div>
    </div>
    
    </body>
    </html>
    
    <!DOCTYPE html>
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8"/>
        <title>user</title>
        <link rel="stylesheet" th:href="@{/css/bootstrap.css}"></link>
    </head>
    <body class="container">
    <br/>
    <h1>添加用户</h1>
    <br/><br/>
    <div class="with:80%">
        <form class="form-horizontal"   th:action="@{/add}"  method="post">
            <div class="form-group">
                <label for="userName" class="col-sm-2 control-label">userName</label>
                <div class="col-sm-10">
                    <input type="text" class="form-control" name="userName"  id="userName" placeholder="userName"/>
                </div>
            </div>
            <div class="form-group">
                <label for="password" class="col-sm-2 control-label" >Password</label>
                <div class="col-sm-10">
                    <input type="password" class="form-control" name="passWord" id="password" placeholder="Password"/>
                </div>
            </div>
            <div class="form-group">
                <label for="age" class="col-sm-2 control-label">age</label>
                <div class="col-sm-10">
                    <input type="text" class="form-control" name="age"  id="age" placeholder="age"/>
                </div>
            </div>
            <div class="form-group">
                <div class="col-sm-offset-2 col-sm-10">
                    <input type="submit" value="Submit" class="btn btn-info" />
                    &nbsp; &nbsp; &nbsp;
                    <input type="reset" value="Reset" class="btn btn-info" />
                </div>
    
            </div>
        </form>
    </div>
    </body>
    </html>
    
    <!DOCTYPE html>
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8"/>
        <title>user</title>
        <link rel="stylesheet" th:href="@{/css/bootstrap.css}"></link>
    </head>
    <body class="container">
    <br/>
    <h1>修改用户</h1>
    <br/><br/>
    <div class="with:80%">
        <form class="form-horizontal"   th:action="@{/edit}" th:object="${user}"  method="post">
            <input type="hidden" name="id" th:value="*{id}" />
            <div class="form-group">
                <label for="userName" class="col-sm-2 control-label">userName</label>
                <div class="col-sm-10">
                    <input type="text" class="form-control" name="userName"  id="userName" th:value="*{userName}" placeholder="userName"/>
                </div>
            </div>
            <div class="form-group">
                <label for="password" class="col-sm-2 control-label" >Password</label>
                <div class="col-sm-10">
                    <input type="password" class="form-control" name="passWord" id="password"  th:value="*{passWord}" placeholder="Password"/>
                </div>
            </div>
            <div class="form-group">
                <label for="age" class="col-sm-2 control-label">age</label>
                <div class="col-sm-10">
                    <input type="text" class="form-control" name="age"  id="age" th:value="*{age}" placeholder="age"/>
                </div>
            </div>
            <div class="form-group">
                <div class="col-sm-offset-2 col-sm-10">
                    <input type="submit" value="Submit" class="btn btn-info" />
                    &nbsp; &nbsp; &nbsp;
                    <a href="/toAdd" th:href="@{/list}" class="btn btn-info">Back</a>
                </div>
    
            </div>
        </form>
    </div>
    </body>
    </html>
    

    效果图

    list.png

    源码地址:https://github.com/WE666/spring-boot-project

    相关文章

      网友评论

          本文标题:Spring Boot 整合 Thymeleaf

          本文链接:https://www.haomeiwen.com/subject/wmjohftx.html