thymeleaf使用实用小功能

「时光不负,创作不停,本文正在参加2021年终总结征文大赛

以此篇文章为thymeleaf相关使用以及功能为记录篇,之后会不定期更新,来充足、记录!

1、thymeleaf中回显表单数据

1.1单选框回显(男女性别为例)

完整版:

前端:th:href="@{/user/load/}+${u.id}",到controller层。

<a title="编辑" th:href="@{/user/load/}+${u.id}" class="ml-5" style="text-decoration:none">
   <i class="Hui-iconfont">&#xe6df;</i>
</a>
复制代码

后端:

(1)控制层接收到回显所需的id值:@PathVariable("id") Integer id

(2)使用model.addAttribute("user",user);绑定user对象。return返回到templates下的user/update.html页面

复制代码
@Controller
@RequestMapping("user")
public class UserController {

    @GetMapping("load/{id}")
    public String load(@PathVariable("id") Integer id,Model model) {

        User user  = userService.selectByPrimaryKey(id);
        model.addAttribute("user",user);
        return "user/update";
    }
}
复制代码

单选框回显:

(1)如果sex属性是int或者Integer数据类型,使用: th:checked=" ${user.sex == 1}"  来对应值,确定选中状态。

(2)如果sex属性是String数据类型,使用 th:checked=" ${uer.sex eq '1'} "  来匹配。

<div class="radio-box">
    <input th:checked="${user.sex} eq '1'" value="1" name="sex" type="radio" id="sex-1" >
    <label for="sex-1">男</label>
</div>
<div  class="radio-box">
    <input th:checked="${user.sex} eq '2'" type="radio" value="2" id="sex-2" name="sex" >
    <label for="sex-2">女</label>
</div>
<div  class="radio-box">
    <input th:checked="${user.sex} ne '1'" type="radio" value="3" id="sex-3" name="sex" >
    <label for="sex-3">保密</label>
</div>

复制代码

2、thymeleaf获取复选框的绑定的id(以批量删除为例)

完整版:

复选框:通过<input type="checkbox" th:value="${u.id}" name="checkboxId">绑定复选框的值为id,之后就是需要获取id的方式了。

<table class="table table-border table-bordered table-hover table-bg table-sort">
   <thead>
      <tr  class="text-c">
         <th width="25"><input type="checkbox" name="" value=""></th>
         <th  width="70">序号</th>
         <th width="100">姓名</th>
         <th width="70">性别</th>
         <th width="130">手机号码</th>
      </tr>
   </thead>
    <tbody>
       <tr th:each="u:${listUser}" class="text-c">
          <td><input type="checkbox" th:value="${u.id}" name="checkbox"></td>
          <td th:text="${uStat.count}">序号</td>
          <td th:text="${u.name}">姓名</td>
          <td th:text="${u.sex}">性别</td>
          <td th:text="${u.telphone}">手机号码</td>

复制代码

点击事件:执行函数funxction()

<a href="javascript:;" onclick="del_user()" class="btn btn-danger radius">
    <i class="Hui-iconfont">&#xe6e2;</i> 批量删除
</a>
复制代码

获取复选框所有绑定的id值:

方法一:通过document.getElementsByName("checkbox");获取所有name="checkbox"且被选中(checked)的id值(通过value=$(u .id)绑定的)的对象,遍历obj获取每一个单选框,通过连接成字符串。

 function del_user() {
    var obj = document.getElementsByName("checkbox");
    var checkedId = "";
    for (k in obj) {
       if (obj[k].checked)
          checkedId += obj[k].value + ",";
    }
复制代码

方法二:通过document.getElementsByName("checkbox");获取所有name="checkbox"且被选中(checked)的id值(通过value=$(u .id)绑定的)的对象,遍历obj,获取每一个单选框,添加到一个数组中。

function del_user() {
  var obj = document.getElementsByName("checkbox");
  var check_arr = [];
 for (var i = 0; i < obj.length; i++) {
    if (obj[i].checked)
        check_arr.push(obj[i].value);
  }
  
}
复制代码

点击事件中通过ajax传入将数据传到后端:(放在function del_user(){ 加入ajax将数据传入后端 })

var flag = window.confirm("你确定要删除这些记录吗");
if(flag){
   $.ajax({
      type:"get",
      url:"/user/delete",//传输到controller成/userdelete路径
      data:{"checkedId":checkedId},
      success:function (msg) {
         alert(msg);
         window.parent.location.reload()//刷新父页面
         var index = parent.layer.getFrameIndex(window.name);
       
         parent.layer.close(index);

      },
       success:function (msg) {
       alert(msg);
       },

   });
}
复制代码

后端:

@ResponseBody:将return返回的数据通过json格式传回.数据为 success:function (msg) {},中的msg

@GetMapping("delete"):请求映射地址的注解,支持get请求。

@RequestMapping("user"):请求映射地址的注解,支持get,post请求。

Strings.isEmpty(checkedId):org.apache.logging.log4j.util包下的一个Strings类判断字符串为空的一个方法。

实现批量删除方法:对于数组:遍历数组,单个删除;对于字符串:先分割成数组,再遍历数组,单个删除。

@Controller
@RequestMapping("user")
public class UserController {

@ResponseBody
@GetMapping("delete")
public String delete(@RequestParam("checkedId") String checkedId) {
    if (Strings.isEmpty(checkedId)){
        return "未选中";
    }
    String[] ids = checkedId.split(",");
    for (int i = 0; i < ids.length; i++) {
        userService.deleteByPrimaryKey(Integer.parseInt(ids[i]));
    }
    return "删除成功";
}

}
复制代码

上一种删除方法可以说是假批量删除,通过在后端循环遍历获取单个数组,然后单个删除,另一种方法,是直接在UserMapper.xml编写批量删除的语法

示例:id="delUser" 对应UserMapper的方法名


<delete id="delUser"  parameterType = "java.util.entity.po.User">
     delete from user where 1>2
         or id in
      <foreach collection="list"  item="id" open="(" separator="," close=")"  >
           #{id}
      </foreach>
 </delete>

复制代码

以此篇文章为thymeleaf相关使用以及功能为记录篇,之后会不定期更新,来充足、记录!

猜你喜欢

转载自juejin.im/post/7036656506237878285