【问题标题】:How can I get the values ​of 1-20 checkboxes from the controller?如何从控制器获取 1-20 个复选框的值?
【发布时间】:2021-11-27 03:46:31
【问题描述】:

如何从控制器中获取1-20个复选框的值?

        <div>
            <ul>
                <li th:each="poi : ${poiList}">
                    <label th:for="${poi.modelName}" th:text="${poi.modelName}">modelName</label>

                    <input type="checkbox" th:id="${poi.modelName}"
                           th:name="${poi.modelName}" th:checked="false"/>
                </li>
            </ul>
        </div>

如上,form标签中有20个复选框。

当按下发送按钮时,只有 poi1~poi20 中选中的 poi 被发送为poi6=on&amp;poi15=on。 这个时候应该如何从控制器中获取值呢?

@PostMapping("/add")
    public String save(
            @RequestParam String poi1,
            @RequestParam String poi2
            ...){
// modelName=%EB%8F%84%EB%A9%B41&poi6=on&poi15=on
        if( poi == null)
        ...
        
    }

不知道有没有比这种方式更好的方法。

【问题讨论】:

  • HTML 标准从不通过 POST 发送未经检查的输入。这就是为什么 Thymeleaf 添加带有下划线的隐藏字段,所以 Spring 知道如何处理它们。使用List&lt;Boolean&gt; poi; 接收字段列表,它可以双向工作。

标签: java spring spring-boot model-view-controller thymeleaf


【解决方案1】:

如果您在 url 中使用多个参数。

您可以注入 HttpServerletRequest 而不是指定完整参数。

@PostMapping("/add")
    public String save(HttpServletRequest req)
        
    }

使用 getParameterNames 或 getParameterMap 方法,它可以帮助您迭代参数列表。 getParameter 方法可以帮助检索特定参数名称的值。

请参考规范:

https://docs.oracle.com/javaee/6/api/javax/servlet/ServletRequest.html#getParameterNames()

第二种方式,在你的方法中使用DTO,spring会自动绑定它的属性。

@PostMapping("/add")
public String save(YourObject obj)
            
        }

确保 YourObject 中的属性名称与参数名称匹配,spring 将使用 getter/setter 来应用值。

您可以参考:

Spring MVC: Complex object as GET @RequestParam

【讨论】:

    猜你喜欢
    • 2012-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多