问题提出:
平台:Richfaces,Jsf,Spring,Ejb3.0
- 页面文件:
- <h:selectOneListboxsize="1"
- value="#{coalDailyBackBean.currentEntity.coalDaily.coalTS}"converter="com.mycompany.CoalTransportStyleConverter">
- <f:selectItemsvalue="#{coalDailyBackBean.allTSs}">
- </f:selectItems>
- </h:selectOneListbox>
<h:selectOneListbox size="1"
value="#{coalDailyBackBean.currentEntity.coalDaily.coalTS}" converter="com.mycompany.CoalTransportStyleConverter">
<f:selectItems value="#{coalDailyBackBean.allTSs}">
</f:selectItems>
</h:selectOneListbox>
coalTS是一个CoalTransportStyle的对象
allTSs是一个CoalTransportStyle的List
- JSF配置文件faces-config.xml:
- <converter>
- <converter-id>
- com.mycompany.CoalTransportStyleConverter
- </converter-id>
- <converter-class>com.mycompany
- .parameter.plantinfo.web.converter.CoalTransportStyleConverter
- </converter-class>
- </converter>
<converter> <converter-id> com.mycompany.CoalTransportStyleConverter </converter-id> <converter-class> com.mycompany .parameter.plantinfo.web.converter.CoalTransportStyleConverter </converter-class> </converter>
CoalTransportStyle.java
- @Entity
- @Table(name="T_CoalTransportStyle")
- publicclassCoalTransportStyleimplementsSerializable{
- /**
- *
- */
- privatestaticfinallongserialVersionUID=-5090574246490412429L;
- privateLongid;
- privateStringparaName;
- @Id
- @GeneratedValue(strategy=GenerationType.AUTO)
- publicLonggetId(){
- returnid;
- }
- publicvoidsetId(Longid){
- this.id=id;
- }
- @Column(unique=true,nullable=false)
- publicStringgetParaName(){
- returnparaName;
- }
- publicvoidsetParaName(StringparaName){
- this.paraName=paraName;
- }
- }
@Entity
@Table(name = "T_CoalTransportStyle")
public class CoalTransportStyle implements Serializable {
/**
*
*/
private static final long serialVersionUID = -5090574246490412429L;
private Long id;
private String paraName;
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@Column(unique=true,nullable=false)
public String getParaName() {
return paraName;
}
public void setParaName(String paraName) {
this.paraName = paraName;
}
}
- publicclassCoalTransportStyleConverterimplementsConverter{
- publicObjectgetAsObject(FacesContextarg0,UIComponentarg1,Stringarg2){
- CoalTransportStylestyle=newCoalTransportStyle();
- Stringstrs[]=arg2.split(":");
- style.setId(newLong(strs[0]));
- style.setParaName(strs[1]);
- returnstyle;
- }
- publicStringgetAsString(FacesContextarg0,UIComponentarg1,Objectarg2){
- CoalTransportStylestyle=(CoalTransportStyle)arg2;
- returnstyle.getId()+":"+style.getParaName();
- }
- }
public class CoalTransportStyleConverter implements Converter {
public Object getAsObject(FacesContext arg0, UIComponent arg1, String arg2) {
CoalTransportStyle style = new CoalTransportStyle();
String strs[] = arg2.split(":");
style.setId(new Long(strs[0]));
style.setParaName(strs[1]);
return style;
}
public String getAsString(FacesContext arg0, UIComponent arg1, Object arg2) {
CoalTransportStyle style = (CoalTransportStyle) arg2;
return style.getId() + ":" + style.getParaName();
}
}
定义了一个converter
- 后台支撑Bean:
- /**
- *获得所有的运输方式
- *
- *@returntheallTSs
- */
- publicList<SelectItem>getAllTSs(){
- allTSs=newArrayList<SelectItem>();
- List<CoalTransportStyle>list=coalTransportStyleService.queryAll(
- "paraName",true);
- for(CoalTransportStylestyle:list){
- allTSs.add(newSelectItem(style,style.getParaName()));
- }
- returnallTSs;
- }
/** * 获得所有的运输方式 * * @return the allTSs */ public List<SelectItem> getAllTSs() { allTSs = new ArrayList<SelectItem>(); List<CoalTransportStyle> list = coalTransportStyleService.queryAll( "paraName", true); for (CoalTransportStyle style : list) { allTSs.add(new SelectItem(style, style.getParaName())); } return allTSs; }- /**
- *@returnthecurrentEntity
- */
- publicCoalDailyEntitygetCurrentEntity(){
- if(getCoalDailyId()!=null){
- currentEntity=newCoalDailyEntity();
- currentEntity.setPlant(plant);
- currentEntity.setT_Date(date);//设置时间
- currentEntity.setCoalDaily(coal);
- }
- returncurrentEntity;
- }
初始页面显示时,h:selectOneListbox显示没有问题,但是当数据提交时,就报了一个错:Validation Error: Value is not valid 上网找了半天也没找到答案,后来自己调试了一下。/** * @return the currentEntity */ public CoalDailyEntity getCurrentEntity() { if (getCoalDailyId() != null) { currentEntity = new CoalDailyEntity(); currentEntity.setPlant(plant); currentEntity.setT_Date(date);// 设置时间 currentEntity.setCoalDaily(coal); } return currentEntity; } - 当数据提交时,是调用了CoalTransportStyleConverter的getAsObject说明这个对象已经创建起来了。但是为什么还报这个错误呢?
- 于是我找了Messages_en.properties错误信息文件。
- javax.faces.component.UISelectOne.INVALID={0}:ValidationError:Valueisnotvalid
javax.faces.component.UISelectOne.INVALID={0}: Validation Error: Value is not valid - 又找到UISelectOne的validateValue方法。
- protectedvoidvalidateValue(FacesContextcontext,Objectvalue){
- //Skipvalidationifitisnotnecessary
- super.validateValue(context,value);
- if(!isValid()||(value==null)){
- return;
- }
- //Ensurethatthevaluematchesoneoftheavailableoptions
- booleanfound=matchValue(value,newSelectItemsIterator(this));
- //Enqueueanerrormessageifaninvalidvaluewasspecified
- if(!found){
- FacesMessagemessage=
- MessageFactory.getMessage(context,INVALID_MESSAGE_ID,
- MessageFactory.getLabel(context,this));
- context.addMessage(getClientId(context),message);
- setValid(false);
- }
- }
- //---------------------------------------------------------PrivateMethods
- /**
- *<p>Return<code>true</code>ifthespecifiedvaluematchesoneofthe
- *availableoptions,performingarecursivesearchififa
- *{@linkSelectItemGroup}instanceisdetected.</p>
- *
- *@paramvalue{@linkUIComponent}valuetobetested
- *@paramitemsIteratoroverthe{@linkSelectItem}stobechecked
- */
- privatebooleanmatchValue(Objectvalue,Iteratoritems){
- while(items.hasNext()){
- SelectItemitem=(SelectItem)items.next();
- if(iteminstanceofSelectItemGroup){
- SelectItemsubitems[]=
- ((SelectItemGroup)item).getSelectItems();
- if((subitems!=null)&&(subitems.length>0)){
- if(matchValue(value,newArrayIterator(subitems))){
- return(true);
- }
- }
- }else{
- //Coercetheitemvaluetypebeforecomparingvalues.
- Classtype=value.getClass();
- ObjectnewValue;
- try{
- newValue=getFacesContext().getApplication().
- getExpressionFactory().coerceToType(item.getValue(),type);
- }catch(ELExceptionele){
- newValue=item.getValue();
- }catch(IllegalArgumentExceptioniae){
- //IfcoerceToTypefails,perthedocsitshouldthrow
- //anELException,however,GF9.0and9.0u1willthrow
- //anIllegalArgumentExceptioninstead(seeGFissue1527).
- newValue=item.getValue();
- }
- if(value.<SPANstyle="COLOR:#ff0000">equals</SPAN>
- (newValue)){
- return(true);
- }
- }
- }
- return(false);
- }
这里调用了equals方法,结果是不行,所以抛出了这个异常。protected void validateValue(FacesContext context, Object value) { // Skip validation if it is not necessary super.validateValue(context, value); if (!isValid() || (value == null)) { return; } // Ensure that the value matches one of the available options boolean found = matchValue(value, new SelectItemsIterator(this)); // Enqueue an error message if an invalid value was specified if (!found) { FacesMessage message = MessageFactory.getMessage(context, INVALID_MESSAGE_ID, MessageFactory.getLabel(context, this)); context.addMessage(getClientId(context), message); setValid(false); } } // --------------------------------------------------------- Private Methods /** * <p>Return <code>true</code> if the specified value matches one of the * available options, performing a recursive search if if a * {@link SelectItemGroup} instance is detected.</p> * * @param value {@link UIComponent} value to be tested * @param items Iterator over the {@link SelectItem}s to be checked */ private boolean matchValue(Object value, Iterator items) { while (items.hasNext()) { SelectItem item = (SelectItem) items.next(); if (item instanceof SelectItemGroup) { SelectItem subitems[] = ((SelectItemGroup) item).getSelectItems(); if ((subitems != null) && (subitems.length > 0)) { if (matchValue(value, new ArrayIterator(subitems))) { return (true); } } } else { //Coerce the item value type before comparing values. Class type = value.getClass(); Object newValue; try { newValue = getFacesContext().getApplication(). getExpressionFactory().coerceToType(item.getValue(), type); } catch (ELException ele) { newValue = item.getValue(); } catch (IllegalArgumentException iae) { // If coerceToType fails, per the docs it should throw // an ELException, however, GF 9.0 and 9.0u1 will throw // an IllegalArgumentException instead (see GF issue 1527). newValue = item.getValue(); } if (value.equals (newValue)) { return (true); } } } return (false); } - 重写CoalTransportStype的equals方法即可:
- @Entity
- @Table(name="T_CoalTransportStyle")
- publicclassCoalTransportStyleimplementsSerializable{
- /**
- *
- */
- privatestaticfinallongserialVersionUID=-5090574246490412429L;
- privateLongid;
- privateStringparaName;
- @Id
- @GeneratedValue(strategy=GenerationType.AUTO)
- publicLonggetId(){
- returnid;
- }
- publicvoidsetId(Longid){
- this.id=id;
- }
- @Column(unique=true,nullable=false)
- publicStringgetParaName(){
- returnparaName;
- }
- publicvoidsetParaName(StringparaName){
- this.paraName=paraName;
- }
- publicbooleanequals(Objectobj){
- if(this==obj)
- returntrue;
- if(obj==null)
- returnfalse;
- if(getClass()!=obj.getClass())
- returnfalse;
- finalCoalTransportStyleother=(CoalTransportStyle)obj;
- if(id==null){
- if(other.id!=null)
- returnfalse;
- }elseif(!id.equals(other.id))
- returnfalse;
- if(paraName==null){
- if(other.paraName!=null)
- returnfalse;
- }elseif(!paraName.equals(other.paraName))
- returnfalse;
- returntrue;
- }
- }
本文解决了一个在JSF框架中使用自定义转换器时出现的“Value is not valid”验证错误。通过重写实体类的equals方法,确保了下拉框选择项的有效性。
74

被折叠的 条评论
为什么被折叠?



