如何使用Spring MVC和ThymeLeaf正确验证复选框?

时间:2018-11-23 20:00:35

标签: javascript java spring spring-mvc thymeleaf

我创建了这个需要进行验证的生物:

enter image description here

这是home.html文件:

<!-- Modal -->
    <div id="vasoModal" class="modal">
        <div class="modal-content">
            <h4 class="modal-title">Vasito</h4>
            <h6>Seleccione hasta dos gustos</h6>
            <form th:action="@{/pedido}" name="vasitoForm" method="post">
                <table class="tabla">
                        <tr th:each="gusto : ${gustos}">
                            <td class="flavour" th:text="${gusto.nombre}"></td>
                            <td><input class="single-checkbox" type="checkbox" th:field="${gusto.id}"/></td>
                        </tr>
                </table>
                <button type="submit" class="btn-submit">Enviar Pedido</button>
            </form>
        </div>
    </div>

所以我现在需要验证单击了哪些按钮,并将其发送到控制器以进行验证:

var checkboxes = document.querySelectorAll('.single-checkbox');
var clicked = [];

checkboxes.forEach(elem => {
    elem.addEventListener('click', (event) => {
        event.stopPropagation();
        alert(elem.value);
        // My logic here was to add the clicked checkboxes to the clicked array and then send that to the controller to validate !!

这是好吗?         });     });

嗯...这里有两个问题...第一个是HTML中的这一行不起作用:

th:field="${gusto.id}"

我无法将每个“ gusto”(西班牙语风味)的ID绑定到复选框(这似乎是一个不错的解决方案)。

我得到的错误如下:

  

Bean名称“ gusto”的BindingResult或普通目标对象均不   可作为请求属性

好吧……我已经在谷歌上搜索并找到了解决方案,但出于我的案例,我没有将“ gustos” ArrayList发送到控制器中的视图。

@RequestMapping(value = "/")
public String getAllProductos(ModelMap modelMap){
    List<Producto> productos = productoService.findAll();
    List<Gusto> gustos = gustoService.findAll();
    modelMap.put("gustos", gustos);
    modelMap.put("productos", productos);
    return "home";
}

所以这个问题有点奇怪!

嗯……第二个问题,就是我在解决该问题之后想要做的……在JS文件中注释了:

  

//我的逻辑是将被单击的复选框添加到被单击的   数组,然后将其发送到控制器以进行验证!

这种方法好吗?有人可以帮我找到更好的复选框错误解决方案吗?

...

1 个答案:

答案 0 :(得分:1)

对于第一个问题,th:field=需要一个*而不是$。尝试将th:field="${gusto.id}"更改为th:field="*{gusto.id}"-文档here

第二次,我不确定这是否是最优雅的方法,但是它一直在为我工作。首先,在POST方法中添加一个HttpServletRequest request(文档here)作为请求参数。您可以从该request中抽出Map<String, String[]>,从中提取数据。然后,您可以使用数据来做您想做的事情:

Map<String, String[]> dataFeed = request.getParameterMap(); // this pulls in the data from the checkboxes

for (Map.Entry<String, String[]> entry : dataFeed.entrySet()) { // this iterates through each entry from the data above
        for (String str : request.getParameterValues(entry.getKey())) { // this loops through the key for each entry 
            Long yourVar = Long.parseLong(entry.getKey()); // assigning the long version of that str to yourVar
            if (str.equals("Yes")) {
                Do something with yourVar // do something with it
            }
            daoObject.save(whatever you've done above);
        }
    }

在您的情况下,也许可以执行以下操作:

@RequestMapping(value="saveGusto", method = RequestMethod.POST)
public String saveGusto(HttpServletRequest request) {

    Map<String, String[]> dataFeed = request.getParameterMap();

    for (Map.Entry<String, String[]> entry : dataFeed.entrySet()) {
        for (String str : request.getParameterValues(entry.getKey())) {
            Long gustoId = Long.parseLong(entry.getKey());
            Gusto gusto = gustoDao.findOne(gId);

            if (str.equals("some-value")) { // where some-value is value="some-value" on your checkbox
                // do something with the gusto
            }
            gustoDao.save(gusto);
        }
    }
}

希望它为您提供了另一种探索途径!