简体   繁体   中英

Dispatcher servlet throws exception: NumberFormatException

I have Controller with @InitBinder that has setAsText method there is exception because for some unknown reason when empty string is passed. Exception:

SEVERE: Servlet.service() for servlet [dispatcher] in context with path [] threw exception [java.lang.NumberFormatException: For input string: ""] with root cause
java.lang.NumberFormatException: For input string: ""

This JSP code causes error:

<div class="form-group">
    <label for="organization">
        <spring:message code="label.organization"></spring:message>:</label>

    <form:select path="organization" class="form-control" id="organization">
        <form:option value="" label="- Select -" />
        <form:options items="${organizations}" itemLabel="name" itemValue="id" />
    </form:select>
</div>

Controller:

@InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(Organization.class,
                new PropertyEditorSupport() {
                    @Override
                    public void setAsText(String text) {
                        Organization organization = organizationService.getOrganization(Integer.parseInt(text));
                        setValue(organization);
                    }
                });
    }

What is wrong? How to make it work?

Update: I don't understand why empty string arrives as parameter to setAsText method. First browser makes request to url, Spring dispatcher servlet serves matching controller's method, then some magic happens where empty string arrives to setAsText method of @InitBinder....

Solved:

 public void setAsText(String text) {
        Object organization;
        if ("".equals(text)) {
            organization = (List < Organization > ) organizationService.getOrganizations();
        } else {
            organization = organizationService.getOrganization(Integer.parseInt(text));
        }

        setValue(organization);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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