springboot中利用thymeleaf实现增删改查

配置文件

pom包配置

pom包里面添加jpa和thymeleaf的相关包引用

<dependency>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-thymeleafartifactId>
dependency>
<dependency>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-data-jpaartifactId>
dependency>
<dependency>
    <groupId>mysqlgroupId>
    <artifactId>mysql-connector-javaartifactId>
dependency>

在application.properties中添加配置

spring.datasource.url=jdbc:mysql://127.0.0.1/test?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC&useSSL=true
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

其中propertiesspring.thymeleaf.cache=false是关闭thymeleaf的缓存,不然在开发过程中修改页面不会立刻生效需要重启,生产可配置为true。

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

启动类

启动类需要添加Servlet的支持

@SpringBootApplication
public class JpaThymeleafApplication extends SpringBootServletInitializer {
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(JpaThymeleafApplication.class);
    }

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

数据库层代码

实体类映射数据库表

@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;
    ...
}

继承JpaRepository类会自动实现很多内置的方法,包括增删改查。也可以根据方法名来自动生成相关sql,具体可以参考:springboot(五):spring data jpa的使用

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

业务层处理

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

@Service
public class UserServiceImpl implements UserService{

    @Autowired
    private UserRepository userRepository;

    @Override
    public List 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 edit(User user) {
        userRepository.save(user);
    }

    @Override
    public void delete(long id) {
        userRepository.delete(id);
    }
}

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

@Controller
public class UserController {

    @Resource
    UserService userService;


    @RequestMapping("/")
    public String index() {
        return "redirect:/list";
    }

    @RequestMapping("/list")
    public String list(Model model) {
        List 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.edit(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请求,然后再输出到页面。

页面内容

list列表

html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"/>
    <title>userListtitle>
    <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 Nameth>
            <th>Passwordth>
            <th>Ageth>
            <th>Editth>
            <th>Deleteth>
        tr>
        thead>
        <tbody>
        <tr  th:each="user : ${users}">
            <th scope="row" th:text="${user.id}">1th>
            <td th:text="${user.userName}">neotd>
            <td th:text="${user.password}">Ottotd>
            <td th:text="${user.age}">6td>
            <td><a th:href="@{/toEdit(id=${user.id})}">edita>td>
            <td><a th:href="@{/delete(id=${user.id})}">deletea>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">adda>
    div>
div>

body>
html>

 这里会从controler层model set的对象去获取相关的内容,th:each表示会循环遍历对象内容。

其实还有其它的写法,具体的语法内容可以参考这篇文章:springboot(四):thymeleaf使用详解

修改页面:

html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"/>
    <title>usertitle>
    <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">userNamelabel>
            <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" >Passwordlabel>
            <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">agelabel>
            <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" />
                     
                <a href="/toAdd" th:href="@{/list}" class="btn btn-info">Backa>
            div>

        div>
    form>
div>
body>
html>

添加页面和修改类似就不在贴代码了。

这样一个使用jpa和thymeleaf的增删改查示例就完成了。

我自己做的时候是利用input标签来先展现用户的属性,之后用户可以修改自己的属性,点击提交的时候可以直接把信息提交给后台,我是利用Ajax来传的值,之后跳转到更改方法中,提交成功后跳转到展示请求

*ajax传参进后台修改数据库*/
                $("#update").click(function () {
                    var name=$("#user-name").val();
                    // var sex1=$("input[name='radio']").val();
                    var email=$("#user-email").val();
                    var telephone=$("#user-phone").val();
                    var age=$("#user-age").val();
                    var birthday=$("#user-birthday").val();
                    var cardId=$("#user-CardId").val();

                    $.ajax({
                        url:"/updateuser", //请求接口地址
                        data:{
//传递给后台接口需要的数
                            name:name,
                            /* sex:'sex1',*/
                            email:email,
                            telphone:telephone,
                            age:age,
                            birthday:birthday,
                            cardId:cardId
                        },
                        success:function (data) {
                            if(data){
                                alert("修改成功")
                              window.location.href="/list"
                            }
                            else{
                                alert("修改失败")
                            }

                        }
                    })
                });
 
  
@RequestMapping(value = "/list", method = RequestMethod.GET)
    public String list(Model model, Integer id) {
        UserInformation userInformation = userService.getUserList(1);
        model.addAttribute("userInformation", userInformation);
        return "wmy/list";
    }
    @ResponseBody
    @RequestMapping(value = "/updateuser", method = RequestMethod.GET)
    public boolean updateuser(String name,String email,String telphone,Integer age,Long birthday,Long cardId) {

        UserInformation userById = userService.findUserById(1);
        userById.setName(name);
        userById.setEmail(email);
        userById.setTelphone(telphone);
        userById.setAge(age);
        userById.setBirthday(birthday);
        userById.setCardId(cardId);
        boolean update = userService.update(userById);
        return update;



//        boolean b = userService.update(userInformation);

    }

你可能感兴趣的:(springboot中利用thymeleaf实现增删改查)