调度程序 servlet 抛出异常:NumberFormatException

Dispatcher servlet throws exception: NumberFormatException

我有带 @InitBinder 的控制器,它有 setAsText 方法,但由于某些未知原因,当传递空字符串时出现异常。例外:

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

此 JSP 代码导致错误:

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

控制器:

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

怎么了?如何让它发挥作用?

更新: 我不明白为什么空字符串作为 setAsText 方法的参数到达。首先浏览器向 url 发出请求,Spring dispatcher servlet 服务于匹配控制器的方法,然后在空字符串到达​​ @InitBinder 的 setAsText 方法时发生一些神奇的事情....

已解决:

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

        setValue(organization);
    }