Dispatcher servlet抛出异常:NumberFormatException

时间:2015-02-20 20:51:26

标签: java jsp spring-mvc

我的控制器@InitBindersetAsText方法存在异常,因为由于某些未知原因传递空字符串。例外:

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调度程序servlet服务于匹配控制器的方法,然后在空字符串到达​​@InitBinder的setAsText方法时发生一些魔术......

1 个答案:

答案 0 :(得分:0)

<强>解决:

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

        setValue(organization);
    }