Need Struts2 boolean converter for yes, no, empty values

I need to save data based on the value selected in the user interface form element.

<s:select key="invoice.productSold" list="${productSold}" /> 

productSold drop-down list of values ​​'' (space), 'Yes', 'No'.

My booleanconverter

 public class BooleanConverter extends StrutsTypeConverter { @Override /*From form*/ public Object convertFromString(Map context, String[] values, Class toClass) { String value = values[0]; if (value == "") { System.out.println("null"); return null; } if ("No".equalsIgnoreCase(value) || "0".equals(value)) { return "false"; } else if ("Yes".equalsIgnoreCase(value) || "1".equals(value)) { return "true"; } else { return null; } } @Override public String convertToString(Map context, Object o) { Boolean value = (Boolean) o; return String.valueOf(value); } } public class Invoice{ Boolean productSold; <getter> <setter> } 

Questions

  • In the "My form" drop-down list, you select "Yes" and update; after updating, my drop-down menu doesn’t show β€œYes”. It appears blank.
  • The ConvertFromString method returns true if Yes is selected on the form and the ConverToString method returns false.

Action class


 public UpdateAction extends ActionSupport{ protected List<String> productSold; public List<String> getProductSold() { List<String> myOptions= new ArrayList<String>(); myOptions.add(""); myOptions.add("Yes"); myOptions.add("No"); return myOptions; } 

+4
source share
2 answers

You do not need a custom logic converter, use the Struts2 internationalization function to get β€œgood” Boolean texts. Put true = Yes and false = No in your message properties, and then use the listValue attribute of the <s:select> to call the getText method to receive messages for true and false .

 <s:select key="invoice.productSold" list="productSold" listValue="%{getText(top)}"/> 

By the way, you do not need to use any "special" notation inside the list attribute to get the value from the value stack.

BTW No. 2: you do not need this productSold method inside your action, instead you can define your yes / no list directly in the JSP using the OGNL notation for lists {...} .

 <s:select key="invoice.productSold" list='{"", true, false}' listValue="%{getText(top)}"/> 
+1
source

Try the following:

 public UpdateAction extends ActionSupport{ protected Map<Object, String> productSold; public Map<Object, String> getProductSold() { Map<Object, String> myOptions= new HashMap<>(); myOptions.put(null, ""); myOptions.put(Boolean.TRUE, "Yes"); myOptions.put(Boolean.FALSE, "No"); return myOptions; } 

And in JSP:

 <s:select key="invoice.productSold" listKey="productSold.key" listValue="productSold.value"/> 
0
source

All Articles