javaservletscheckboxmultipartform-dataapache-commons-fileupload

Elegant way to get boolean from checkbox using Apache FileItem


There is the form with the checkbox input:

<form action='${pageContext.request.contextPath}/register' method="POST"
      enctype="multipart/form-data">

        <div>
            <label class="form-check-label">
                <input id="news_feed" name="news_feed" class="form-check-input" type="checkbox" value="${sessionScope.bean.interestedInNewsFeed}">
                I want to receive updates via email.
            </label>
        </div>
</form>

In my servlet I'm trying to receive the value:

List<FileItem> multiparts = new ServletFileUpload(
                        new DiskFileItemFactory()).parseRequest(req);
                boolean interestedInNewsFeed = Boolean.parseBoolean(multiparts.stream().filter((x) -> x.getFieldName().equals("news_feed")).
                        findFirst().get().getString());

However, I'm getting the exception:

java.util.NoSuchElementException: No value present

I tried to see returned string:

  1. If checkbox is checked then empty string is returned.
  2. If checkbox isn't checked - exception is thrown.

How can I parse the checkbox value into boolean using FileItem class of Apache-Commons-FileUpload library without getting the exception?

I googled the question but can't find any relevant information.


Solution

  • Only checked checkboxes are part of the form post. Therefore, the most straightforward solution would be

    boolean interestedInNewsFeed = multiparts.stream().filter((x) -> x.getFieldName().equals("news_feed"))
                    .findAny().isPresent();