springboot-jpa-thymeleaf

来源:互联网 发布:mac上安装jmeter 编辑:程序博客网 时间:2024/06/05 05:28

上次说道springboot整合持久层mybatis,今天换一个持久层进行整合,并且配合一款j模版引擎thymeleaf实现一个登录的功能

jpa简介

JPA是Java Persistence API的简称,中文名Java持久层API,是JDK 5.0注解或XML描述对象-关系表的映射关系,并将运行期的实体对象持久化到数据库中,Jpa是一种规范,而持久层的老框架Hibernate是它的一种实现其实,jpa代码运用中更简洁,但是jpa与mybatis到底哪个更好更适合还要根据具体的开发情景。

thymeleaf简介

Thymeleaf是一款用于渲染XML/XHTML/HTML5内容的模板引擎。类似JSP,Velocity,FreeMaker等,它也可以轻易的与Spring MVC等Web框架进行集成作为Web应用的模板引擎。与其它模板引擎相比,Thymeleaf最大的特点是能够直接在浏览器中打开并正确显示模板页面,而不需要启动整个Web应用。支持el以及jstl等

整合过程

  1. 利用maven快速创建springboot的工程(前面有介绍)

  2. 打开pom.xml引入相应的依赖

<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.demo</groupId>  <artifactId>springboot-jpa-thymeleaf</artifactId>  <version>0.0.1-SNAPSHOT</version>  <packaging>jar</packaging>  <name>springboot-jpa-thymeleaf</name>  <url>http://maven.apache.org</url>  <parent>        <groupId>org.springframework.boot</groupId>        <artifactId>spring-boot-starter-parent</artifactId>        <version>1.5.6.RELEASE</version>    </parent>  <properties>    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>    <java.version>1.8</java.version>  </properties><dependencies>  <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-web</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-data-jpa</artifactId>        </dependency>        <dependency>            <groupId>mysql</groupId>            <artifactId>mysql-connector-java</artifactId>        </dependency>    <dependency>      <groupId>junit</groupId>      <artifactId>junit</artifactId>      <version>3.8.1</version>      <scope>test</scope>    </dependency>  </dependencies>   <build>        <plugins>            <plugin>                <groupId>org.springframework.boot</groupId>                <artifactId>spring-boot-maven-plugin</artifactId>                <configuration>                    <fork>true</fork>                </configuration>            </plugin>        </plugins>    </build></project>

紧接着配置application.properties:
spring.datasource.url=jdbc:mysql://localhost:3306/springbootdb?useUnicode=true&characterEncoding=utf8&useSSL=false
spring.datasource.username=root
spring.datasource.password=root
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

spring.thymeleaf.cache=false
server.port=8888

3.新建用户实体并且与数据库表的列字段对应:

@Entity@Table(name = "user")public class User implements Serializable{    private static final long serialVersionUID = 1L;    @Id    @GeneratedValue    private Integer id;//ID主键    @Column(name = "user_name")    private String userName;//用户名    @Column(name = "pass_word")    private String passWord;//密码    @Column(name = "user_email")    private String email;//邮箱    @Column(name = "user_phone")    private String phone;//电话    @Column(name = "user_sex")    private String sex;//性别    @Column(name = "user_birthday")    private String birthday;//出生年月    @Column(name = "reg_time")    private String regTime;//注册时间    public User() {        super();    }    public User(Integer id, String userName, String passWord, String email,            String phone, String sex, String birthday, String regTime) {        super();        this.id = id;        this.userName = userName;        this.passWord = passWord;        this.email = email;        this.phone = phone;        this.sex = sex;        this.birthday = birthday;        this.regTime = regTime;    }    public Integer getId() {        return id;    }    public void setId(Integer id) {        this.id = id;    }    public String getUserName() {        return userName;    }    public void setUserName(String userName) {        this.userName = userName;    }    public String getPassWord() {        return passWord;    }    public void setPassWord(String passWord) {        this.passWord = passWord;    }    public String getEmail() {        return email;    }    public void setEmail(String email) {        this.email = email;    }    public String getPhone() {        return phone;    }    public void setPhone(String phone) {        this.phone = phone;    }    public String getSex() {        return sex;    }    public void setSex(String sex) {        this.sex = sex;    }    public String getBirthday() {        return birthday;    }    public void setBirthday(String birthday) {        this.birthday = birthday;    }    public String getRegTime() {        return regTime;    }    public void setRegTime(String regTime) {        this.regTime = regTime;    }}

新建dao并且继承与JpaRepository:

这里写代码片public interface UserDao extends JpaRepository<User, Integer>{    User findById(Integer id);    User findByUserName(String userName);    Integer deleteById(Integer id);    User findByUserNameAndPassWord(String userName,String passWord);}

新建service服务类以及实现类:

这里写代码片public interface UserService {    public List<User> getUserList();    public User findUserById(Integer id);    public void save(User user);    public void edit(User user);    public void delete(Integer id);    public User findByUserNameAndPassword(String userName,String passWord);    public Page<User> findALL(Pageable pageable);}@Servicepublic class UserServiceImpl implements UserService{    @Autowired    private UserDao userDao;    @Autowired    /**     *      * <p>Title: getUserList</p>        * <p>Description:获取用户列表 </p>        * @return        * @see com.ch.service.UserService#getUserList()     */    public List<User> getUserList() {        List<User> userList = new ArrayList<User>();        userList = userDao.findAll();        return userList;    }    public User findUserById(Integer id) {        User user = new User();        user = userDao.findById(id);        return user;    }    public void save(User user) {        user.setRegTime(DateUtil.getDateFormat(new Date()));        userDao.save(user);    }    public void edit(User user) {        user.setRegTime(userDao.findById(user.getId()).getRegTime());        userDao.save(user);    }    public void delete(Integer id) {        userDao.delete(id);    }    /**     *      * <p>Title: findByUserNameAndPassword</p>        * <p>Description: 根据用户名密码查询用户</p>        * @param userName     * @param passWord     * @return        * @see com.ch.service.UserService#findByUserNameAndPassword(java.lang.String, java.lang.String)     */    public User findByUserNameAndPassword(String userName, String passWord) {        User user = new User();        user = userDao.findByUserNameAndPassWord(userName, passWord);        return user;    }    public Page<User> findALL(Pageable pageable) {        return userDao.findAll(pageable);    }

4.controller的实现

这里写代码片@Controllerpublic class UserController {    @Resource    UserService userService;    private Log logger = LogFactory.getLog(UserController.class);    /**     *      * @Title: index        * @Description: 登录页面        * @param: @return           * @return: String           * @throws     */    @RequestMapping("/")    public String index() {        return "user/index";    }    /**     *      * @Title: login        * @Description: 登录        * @param: @return           * @return: String           * @throws     */    @RequestMapping("/login")    public String login(String userName,String passWord) {        User user = userService.findByUserNameAndPassword(userName, passWord);        if(user==null){            return "user/index";        }else{            return "redirect:/list";        }    }    /**     * 获取用户列表     *      */    @RequestMapping("/list")    public String list(Model model) {        List<User> users = userService.getUserList();        model.addAttribute("users", users);        return "user/list";    }    /**     * 分页查询所有用户列表     *      */    @RequestMapping("/listPage")    public String listPage(Model model, Integer pageNum) {        int page = 0;        int size = 5;// 每页记录条数        page = 1;        // Sort sort = new Sort(Direction.DESC, "id");        // Pageable pageable = new PageRequest(page, size, sort);        Pageable pageable = new PageRequest(page, size);        Page<User> userpage = userService.findALL(pageable);        model.addAttribute("pageable", pageable);        model.addAttribute("userpage", userpage);        return "user/listPage";    }    /**     * 跳转到用户注册页面     *      */    @RequestMapping("/toAdd")    public String toAdd() {        return "user/userAdd";    }    /**     * 添加保存用户并返回列表页面     *      */    @RequestMapping("/add")    public String add(User user) {        userService.save(user);        return "redirect:/listPage";    }}

5.后台的代码都有了但是没有对应的页面代码,在resources下新建templates文件夹再在其下新建user文件夹,新建index.html,list.html,listPage等页面:
index.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 align="center"><a th:href="@{/}">用户登录</a></h1><br/><br/><div class="with:80%">        <form class="form-horizontal" th:action="@{/login}" method="post" align="center">            <span>用户名:</span>             <input name="userName" type="text"/> <br/>            <span>密&nbsp;&nbsp;&nbsp;&nbsp;码:</span>             <input name="passWord" type="text"/><br/>            <input type="submit" value="登录" class="btn btn-info"/>            <input type="reset" value="重置" class="btn btn-info"/>            <a href="/toAdd" th:href="@{/toAdd}" class="btn btn-info">注册</a>        </form></div></body></html>

list.html:

<!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><a th:href="@{/}">用户列表</a></h1><br/><br/><div class="with:80%">    <table class="table table-hover">        <thead>        <tr>            <th colspan="3">                <form class="form-horizontal" th:action="@{/findByUserName}" method="post">                    <span>用户名:</span>                     <input name="userName" type="text" placeholder="输入用户名查询"/>                     <input type="submit" value="查询" class="btn btn-info"/>                </form>            </th>               <th colspan="3">                    <form class="form-horizontal" th:action="@{/findByUserNameOrEmail}" method="post">                    <span>用户/邮箱:</span>                     <input name="userName" type="text" placeholder="输入用户名或者邮箱查询"/>                     <input type="submit" value="查询" class="btn btn-info"/>                </form>            </th>                   <th colspan="3">                    <form class="form-horizontal" th:action="@{/findByEmailLike}" method="post">                    <span>邮箱:</span>                     <input name="email" type="text" placeholder="输入邮箱模糊查询"/>                     <input type="submit" value="查询" class="btn btn-info"/>                </form>            </th>        </tr>        </thead>        <thead>        <tr>            <th colspan="3">                <form class="form-horizontal" th:action="@{/findByUserNameIgnoreCase}" method="post">                    <span>用户名:</span>                     <input name="userName" type="text" placeholder="不考虑大小写查找用户查询"/>                     <input type="submit" value="查询" class="btn btn-info"/>                </form>            </th>               <th colspan="3">                <form class="form-horizontal" th:action="@{/findByUserNameOrderByEmailDesc}" method="post">                    <span>邮箱名:</span>                     <input name="userName" type="text" placeholder="根据userName查找用户列表并根据email降序排列"/>                     <input type="submit" value="查询" class="btn btn-info"/>                </form>            </th>               <th colspan="2"></th>            <th class="col-sm-2 control-label">                <a href="/toAdd" th:href="@{/toAdd}" class="btn btn-info">新增</a>            </th>        </tr>        </thead>        <thead>        <tr>            <th>ID主键</th>            <th>用户名</th>            <th>密码</th>            <th>邮箱</th>            <th>电话</th>            <th>性别</th>            <th colspan="2">出生年月</th>            <th colspan="2">注册时间</th>            <th>修改用户</th>            <th>删除用户</th>        </tr>        </thead>        <tbody>        <tr  th:each="user : ${users}">            <td scope="row" th:text="${user.id}"></td>            <td th:text="${user.userName}"></td>            <td th:text="${user.passWord}"></td>            <td th:text="${user.email}"></td>            <td th:text="${user.phone}"></td>            <td th:text="${user.sex}"></td>            <td th:text="${user.birthday}" colspan="2"></td>            <td th:text="${user.regTime}" colspan="2"></td>            <td><a th:href="@{/toEdit(id=${user.id})}">修改</a></td>            <td><a th:href="@{/delete(id=${user.id})}">删除</a></td>        </tr>        </tbody>    </table></div></body></html>

其余页面不在这里粘贴了,可自行去下载。
6.工程目录如下:
这里写图片描述

7.打开游览器访问:http://localhost:8888/ 进入登录页面:
这里写图片描述

输入用户名密码后登录:
这里写图片描述

代码地址:
https://gitee.com/chenghao842822530/springbootdemo

下文预告:下次对springboot和redis进行整合

上一篇springboot+mybatis:http://blog.csdn.net/helloword_monkey/article/details/78804671

原创粉丝点击