简体   繁体   English

Thymeleaf 复选框未传递值

[英]Thymeleaf checkbox not passing value

two problems.两个问题。

  1. I have User and Note classes.我有 User 和 Note 类。 User can have many notes.用户可以有很多笔记。 How to show by Thymeleaf every id of notes which belong to user ?如何通过 Thymeleaf 显示属于用户的笔记的每个 id? th:text="${u.notes.id}" doesn't work th:text="${u.notes.id}" 不起作用
  2. I have table(see picture) with checkboxes for every user with boolean isUserChecked value, below is button to delete checked user.我有带有布尔值 isUserChecked 值的每个用户的复选框(见图片),下面是删除选中用户的按钮。 Thymeleaf correct shows state of isUserChecked values. Thymeleaf 正确显示 isUserChecked 值的状态。 Delete button doesn't work when i check checkbox by hand but works when i set isUserChecked values in code.当我手动选中复选框时,删除按钮不起作用,但当我在代码中设置 isUserChecked 值时起作用。 So problem is in my Thymeleaf syntax of this checkbox.所以问题出在这个复选框的 Thymeleaf 语法​​中。

Screenshot:截屏:

在此处输入图片说明

html 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>

UPDATE 1更新 1

as @Metroids mentioned first problem can fix by:正如@Metroids 提到的,第一个问题可以通过以下方式解决:

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

Second problem.第二个问题。 For using this in my html:在我的 html 中使用它:

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

i need UserWrapper class with property List<User> listOUsers .我需要带有属性List<User> listOUsers UserWrapper 类。 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";
}
}

after this i have error:在此之后我有错误:

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

UPDATE 2更新 2

User controller:用户控制器:

@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());
        }
    }
}

Result:结果:

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 part wokrs great now, but my list from userWrap doesn't have values when i call POST method in controller. Thymeleaf 部分现在很棒,但是当我在控制器中调用 POST 方法时,我的 userWrap 列表没有值。 I was trying copy我正在尝试复制

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

to POST method but there was situation: usernames: OK, checked?: doesn't listen mouse clicking to checkbox (all values are false). POST 方法,但有情况:用户名:好的,已检查?:不听鼠标单击复选框(所有值均为假)。

For the listing the id of every note you need to add another loop.为了列出每个音符的 id,您需要添加另一个循环。 For example, instead of例如,代替

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

You need something like.你需要类似的东西。

<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...你需要做出很多改变……

  • All the checkboxes need to be within the <form></form> tags.所有复选框都需要在<form></form>标签内。
  • 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.您需要一个将用户列表作为属性的命令对象...我认为您不能使用 java List 作为命令对象。 That needs to be specified as the th:object on the <form> tag.这需要被指定为<form>标签上的 th:object。
  • The html for the actual checkbox should look something like this:实际复选框的 html 应如下所示:

HTML 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控制器

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM