Pick Custom Object from Select one menu JSF [duplicate]

会有一股神秘感。 提交于 2019-12-02 03:08:51
skuntsel

You are trying to map a Java object of class Currency to a string that comes as a HTTP request parameter. A converter is intended to be used in a situation when you need to create an object from a its string representation, and vice versa, like in the situation you faced.

Basically there are two approaches.

1. Utilize converter.

With this approach you define item value as a Currency object and use a converter to create string representation from an object and recreate an object back from a string. For the converter part, just follow the tutorial Luiggi pointed at. Basically you need to create a class that implements Converter, annotate it with @FacesConverter("currencyConverter") to be able to refer to the converter by id, like in converter="currencyConverter" attribute of a JSF tag:

<p:selectOneMenu id="CurrencyMenu" value="#{CurrencyMB.currency}" converter="currencyConverter">
    <f:selectItems value="#{CurrencyMB.currencyList}" var="currency"  itemValue="#{currency}" itemLabel="#{currency.currencyName}" /> 
    <p:ajax update="currencyOut" />
</p:selectOneMenu>

2. Utilize plain Strings (or java primitive wrappers).

With this approach you bind item values, as well as user selection to a bean property of String type, and not to an actual object. Using it this way you won't need any converter, and string values will be set for you:

<p:selectOneMenu id="CurrencyMenu" value="#{CurrencyMB.currencyName}">
    <f:selectItems value="#{CurrencyMB.currencyList}" var="currency"  itemValue="#{currency.currencyName}" itemLabel="#{currency.currencyName}" /> 
    <p:ajax update="currencyOut" />
</p:selectOneMenu>

Finally, it is worth reading the question to the answer Why selectOneMenu Send ItemLabel to the converter?.

You can create Converter for your Custom Object Currency.

Step 1: Create a Converter class and Implement javax.faces.convert.Converter Interface,Override getAsObject and getAsString methods and write your logic for String to Object Conversion and Object to String Conversion.

Step 2: Simply declare something like @FacesConverter("currencyConverter") in your converter class or If you want use Spring Inject or Autowired Annotation in Converter class declare your Converter Class with @Component("currencyConverter") Annotation and don't use @FacesConverter.And your converter class should in component scan package.

Step 3: Declare your converter in Selectonemenu Using converter property.

If you still have any problem please refer this link

http://www.techpages.org/jsf/jsf-custom-object-converter-from-selectonemenu/2428/

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