1

How can I get the values ​​of 1-20 checkboxes from the controller?

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

As above, there are 20 checkboxes in the form tag.

When the send button is pressed, only the checked poi among poi1~poi20 is sent as poi6=on&poi15=on. How should I get the value from the controller at this time?

@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)
        ...
        
    }

I wonder if there is a better way than this way.

ringhiosi
  • 111
  • 6
  • The HTML standard never sends unchecked inputs through the POST. This is why Thymeleaf adds hidden fields with an underscore, so Spring knows what to do with them. Use `List poi;` to receive a list of fields, it works both directions. – Guillaume F. Oct 07 '21 at 04:10

1 Answers1

-1

In case you use multiple parameters in url.

You can inject HttpServerletRequest instead of specifying full parameters.

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

With getParameterNames or getParameterMap method, it can help you to iterate the list of parameters. getParameter method can help to retrieve the value of specific param name.

Please refer to spec:

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

The second way, use DTO in your method, spring will auto bind its properties.

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

Make sure the attribute name in YourObject match with parameter name, spring will use getter/setter to apply the value.

You can refer at:

Spring MVC: Complex object as GET @RequestParam

Huy Nguyen
  • 1,931
  • 1
  • 11
  • 11