How to preserve NULL state in a Boolean sending an empty String from JSP to Action

两盒软妹~` 提交于 2019-12-08 02:18:14

问题


I have a criterion in a search page that is a boolean. Since it is not mandatory, I can't use a checkbox, because I may want to skip it;

JSP

<s:select list = '#{ "":"Make your choice...", true:"FOO", false:"BAR" }'
          name = "myBooleanCriterion" />

Action

private Boolean myBooleanCriterion;

/* Getter and Setter */

We know that boolean defaults to false, while Boolean defaults to null, then the first time the page is rendered, it is ok ("Make your choice" is displayed).

After the POST, however, Struts instantiates the Boolean property (defaulting it to false) even when it finds "" as value, so when I come back to the JSP, the value is preselected to false ("BAR").

How can I instruct Struts to not create an instance of that variable if the value is "", leaving it to its original, null state ? Do I need to create a Converter, or to specify something in the .properties file ? (I've basically the same code as in example .2 from this answer)

I'm using (a slightly custom) paramsPrepareParamsStack Interceptor Stack.

I feel like if I'm missing something stupid.


回答1:


Because the XWorkBasicConverter converts boolean-s exactly the same way it converts Boolean-s, by using Boolean.valueOf() method, the empty string or null will be converted to false.

In order to have null after submit you need to create a custom converter for Boolean or don't submit this parameter at all. (E.g. Change name attribute with javascript if selected value is "").



来源:https://stackoverflow.com/questions/22255612/how-to-preserve-null-state-in-a-boolean-sending-an-empty-string-from-jsp-to-acti

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!