Thymeleaf复选框没有传递值 [英] Thymeleaf checkbox not passing value

查看:2180
本文介绍了Thymeleaf复选框没有传递值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

两个问题。


  1. 我有User和Note类。用户可以有很多笔记。如何通过Thymeleaf展示属于用户的每个笔记? th:text =$ {u.notes.id}不起作用

  2. 我有表格(见图片),每个用户的复选框都有布尔值isUserChecked值,下面是按钮删除已检查的用户Thymeleaf正确显示isUserChecked值的状态。当我手动选中复选框时,删除按钮不起作用,但是当我在代码中设置isUserChecked值时,该按钮有效。问题在于我的Thymeleaf语法中的这个复选框。

屏幕截图:

html

<div class="container">
<div class="row">
        <div class="col-sm-6">
              <table class="table table-hover">
                <thead>
                  <tr>
                    <th>Id</th>
                    <th>Username</th>
                    <th>First name</th>
                    <th>Last name</th>
                    <th>Password (Hash)</th>
                    <th>Role</th>
                    <th>Notes</th>
                    <th>Select</th>
                  </tr>
                </thead>
                <tbody>
                  <tr th:each="u : ${listOfUsers}">
                    <td th:text="${u.id}"></td>
                    <td th:text="${u.username}"></td>
                    <td th:text="${u.firstName}"></td>
                    <td th:text="${u.lastName}"></td>
                    <td th:text="${#strings.substring(u.password,0,5) +'...'}"></td>
                    <td th:text="${u.role}"></td>
                    <td th:text="${u.notes}"></td>     
                    <td><input type="checkbox" name="mycheckbox" 
                     th:value="*{u.isUserChecked()}" th:checked="${u.isUserChecked()}"  /></td>
                  </tr>
                </tbody>
              </table>

            <form th:action="@{/users}" method="post">
                <button class="buttonLogin" type="submit">Submit</button>
            </form>
        </div>
  </div>

更新1

正如@Metroids提到的第一个问题可以解决:

as @Metroids mentioned first problem can fix by:

< td>< span th:each =note,i: $ {u.notes}th:text =$ {(i.index> 0?',':'')+ note.id}/>< / td>

第二个问题。在我的html中使用它:

Second problem. For using this in my html:

<tr th:each="u, i : ${userWrapper}">
<!-- other rows removed for readability -->
<td><input type="checkbox" th:field="*{listOfUsers[__${i.index}__].userChecked}" /></td>

我需要带有属性的UserWrapper类列表<使用者> listOUsers 。但是怎么做呢?
我创建了这样的东西:

i need UserWrapper class with property List<User> listOUsers. But how to do this ? I created something like this:

@Component
public class UserWrapper {

@Autowired
UserService userService;

List<User> listOfUsers = userService.findAll();

public List<User> getListOfUsers() {
    return listOfUsers;
}

public void setListOfUsers(List<User> listOfUsers) {
    this.listOfUsers = listOfUsers;
}
}

以下是此页面的控制器:

Here is my controller for this page:

@Controller
public class UserController {

@Autowired
UserService userService;

@Autowired 
UserWrapper userWrapper;

@RequestMapping("/users")
public String home(Model model){
    List<User> listOfUsers = userService.findAll();
    model.addAttribute("listOfUsers", listOfUsers);
    return "users";
}

@RequestMapping(value = "users", method = RequestMethod.POST)
public String deleteUser(User user, Model model){
    userService.deleteCheckedUser(user);

    return "redirect:/users";
}
}

此后我有错误:

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userController': Unsatisfied dependency expressed through field 'userWrapper'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userWrapper' defined in file [C:\Users\luk89\Desktop\Java\STS Projects\StickyNotes\target\classes\com\twistezo\models\UserWrapper.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.twistezo.models.UserWrapper]: Constructor threw exception; nested exception is java.lang.NullPointerException

更新2

用户控制器:

@Controller
public class UserController {

@Autowired
UserService userService;

@Autowired
UserWrapper userWrapper;

@RequestMapping("/users")
public String home(Model model){
    List<User> listOfUsers = userService.findAll();
    userWrapper.setListOfUsers(listOfUsers);

    for(User u : userWrapper.getListOfUsers()){
        System.out.println("username: " +u.getUsername()+ ", checked?: " +u.isUserChecked());
    }

    model.addAttribute("listOfUsers", listOfUsers);
    model.addAttribute("userWrapper", userWrapper);

    return "users";
}

@RequestMapping(value = "/users", method = RequestMethod.POST)
public String deleteUser(@ModelAttribute UserWrapper userWrapper, Model model){

    for(User u : userWrapper.getListOfUsers()){
        System.out.println("username: " +u.getUsername()+ ", checked?: " +u.isUserChecked());
    }

    userService.deleteCheckedUser(userWrapper);

    return "redirect:/users";
    }
}

从我的服务类中删除方法:

Delete method from my service class:

@Override
public void deleteCheckedUser(UserWrapper userWrapper) {

    for(User u : userWrapper.getListOfUsers()){
        if(u.isUserChecked() == true){
            this.userDAO.delete(u.getId());
        }
    }
}

结果:

username: user1, checked?: false
username: user2, checked?: false
username: user3, checked?: false
username: user4, checked?: false
username: user5, checked?: false
username: asd, checked?: false
username: qwe, checked?: false
username: xcv, checked?: false
username: ghj, checked?: false
username: dfh, checked?: false
username: n, checked?: false
username: ed, checked?: false

username: null, checked?: true
username: null, checked?: false
username: null, checked?: false
username: null, checked?: false
username: null, checked?: false
username: null, checked?: false
username: null, checked?: false
username: null, checked?: false
username: null, checked?: false
username: null, checked?: false
username: null, checked?: false
username: null, checked?: true

Thymeleaf部分现在很棒,但是当我在控制器中调用POST方法时,我的userWrap列表没有值。我正在尝试复制

Thymeleaf part wokrs great now, but my list from userWrap doesn't have values when i call POST method in controller. I was trying copy

List< User> listOfUsers = userService.findAll();
userWrapper.setListOfUsers(listOfUsers);

到POST方法但是有这样的情况:用户名:好的,检查了吗?:没有' t听鼠标点击复选框(所有值都为false)。

to POST method but there was situation: usernames: OK, checked?: doesn't listen mouse clicking to checkbox (all values are false).

推荐答案

列表中需要添加的每个音符的id另一个循环。例如,代替

For the listing the id of every note you need to add another loop. For example, instead of

<td th:text="${u.notes}"></td>

你需要类似的东西。

<td><span th:each="note, i: ${u.notes}" th:text="${(i.index > 0 ? ', ' : '') + note.id}" /></td>

-

复选框。您需要进行大量更改...

For the checkbox. You have a lot of changes you need to make...


  • 所有复选框都必须位于< ; form>< / form> tags。

  • 您需要一个具有用户列表作为属性的命令对象...我不认为您可以使用java List作为命令对象。需要将其指定为< form> 标记上的th:对象。

  • 实际复选框的html应该看起来如此类似这样的事情:

  • All the checkboxes need to be within the <form></form> tags.
  • You need a command object that has a list of users as a property... I don't think you can use a java List as the command object. That needs to be specified as the th:object on the <form> tag.
  • The html for the actual checkbox should look something like this:

HTML

<form th:action="@{/users}" th:object="${userWrapper}" method="post">
    <!-- other html removed for readability -->
    <tr th:each="u, i : ${listOfUsers}">
        <!-- other rows removed for readability -->
        <td><input type="checkbox" th:field="*{users[__${i.index}__].userChecked}" /></td>
    </tr>
</form>

控制器

@Controller
public class UserController {

    @Autowired UserService userService;

    @RequestMapping("/users")
    public String home(Model model){
        List<User> listOfUsers = userService.findAll();
        UserWrapper userWrapper = new UserWrapper();
        userWrapper.setListOfUsers(listOfUsers);
        model.addAttribute("listOfUsers", listOfUsers);
        model.addAttribute("userWrapper", userWrapper);
        return "users";
    }

    @RequestMapping(value = "users", method = RequestMethod.POST)
    public String deleteUser(@ModelAttribute UserWrapper userWrapper, Model model){
        userService.deleteCheckedUser(userWrapper.getListOfUsers());
        return "redirect:/users";
    }
}

Java

public class UserWrapper {
    List<User> listOfUsers = new ArrayList<>();

    public List<User> getListOfUsers() {
        return listOfUsers;
    }

    public void setListOfUsers(List<User> listOfUsers) {
        this.listOfUsers = listOfUsers;
    }
}

这篇关于Thymeleaf复选框没有传递值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆