JSF Validation Error: Value is not valid(值无效)错误解决一

问题提出:

平台:Richfaces,Jsf,Spring,Ejb3.0

  • 页面文件:
Html代码 复制代码
  1. <h:selectOneListboxsize="1"
  2. value="#{coalDailyBackBean.currentEntity.coalDaily.coalTS}"converter="com.mycompany.CoalTransportStyleConverter">
  3. <f:selectItemsvalue="#{coalDailyBackBean.allTSs}">
  4. </f:selectItems>
  5. </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:
Xml代码 复制代码
  1. <converter>
  2. <converter-id>
  3. com.mycompany.CoalTransportStyleConverter
  4. </converter-id>
  5. <converter-class>com.mycompany
  6. .parameter.plantinfo.web.converter.CoalTransportStyleConverter
  7. </converter-class>
  8. </converter>
<converter>

	<converter-id>

		com.mycompany.CoalTransportStyleConverter

	</converter-id>

	<converter-class>		com.mycompany

.parameter.plantinfo.web.converter.CoalTransportStyleConverter

	</converter-class>

</converter>

CoalTransportStyle.java

Java代码 复制代码
  1. @Entity
  2. @Table(name="T_CoalTransportStyle")
  3. publicclassCoalTransportStyleimplementsSerializable{
  4. /**
  5. *
  6. */
  7. privatestaticfinallongserialVersionUID=-5090574246490412429L;
  8. privateLongid;
  9. privateStringparaName;
  10. @Id
  11. @GeneratedValue(strategy=GenerationType.AUTO)
  12. publicLonggetId(){
  13. returnid;
  14. }
  15. publicvoidsetId(Longid){
  16. this.id=id;
  17. }
  18. @Column(unique=true,nullable=false)
  19. publicStringgetParaName(){
  20. returnparaName;
  21. }
  22. publicvoidsetParaName(StringparaName){
  23. this.paraName=paraName;
  24. }
  25. }
@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;

	}

}

Java代码 复制代码
  1. publicclassCoalTransportStyleConverterimplementsConverter{
  2. publicObjectgetAsObject(FacesContextarg0,UIComponentarg1,Stringarg2){
  3. CoalTransportStylestyle=newCoalTransportStyle();
  4. Stringstrs[]=arg2.split(":");
  5. style.setId(newLong(strs[0]));
  6. style.setParaName(strs[1]);
  7. returnstyle;
  8. }
  9. publicStringgetAsString(FacesContextarg0,UIComponentarg1,Objectarg2){
  10. CoalTransportStylestyle=(CoalTransportStyle)arg2;
  11. returnstyle.getId()+":"+style.getParaName();
  12. }
  13. }
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:
    Java代码 复制代码
    1. /**
    2. *获得所有的运输方式
    3. *
    4. *@returntheallTSs
    5. */
    6. publicList<SelectItem>getAllTSs(){
    7. allTSs=newArrayList<SelectItem>();
    8. List<CoalTransportStyle>list=coalTransportStyleService.queryAll(
    9. "paraName",true);
    10. for(CoalTransportStylestyle:list){
    11. allTSs.add(newSelectItem(style,style.getParaName()));
    12. }
    13. returnallTSs;
    14. }
    /**
    
     * 获得所有的运输方式
    
     * 
    
     * @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;
    
    }
    Java代码 复制代码
    1. /**
    2. *@returnthecurrentEntity
    3. */
    4. publicCoalDailyEntitygetCurrentEntity(){
    5. if(getCoalDailyId()!=null){
    6. currentEntity=newCoalDailyEntity();
    7. currentEntity.setPlant(plant);
    8. currentEntity.setT_Date(date);//设置时间
    9. currentEntity.setCoalDaily(coal);
    10. }
    11. returncurrentEntity;
    12. }
    /**
    
     * @return the currentEntity
    
     */
    
    public CoalDailyEntity getCurrentEntity() {
    
    	if (getCoalDailyId() != null) {
    
    		currentEntity = new CoalDailyEntity();
    
    		currentEntity.setPlant(plant);
    
    		currentEntity.setT_Date(date);// 设置时间
    
    		currentEntity.setCoalDaily(coal);
    
    	}
    
    	return currentEntity;
    
    }
    初始页面显示时,h:selectOneListbox显示没有问题,但是当数据提交时,就报了一个错:Validation Error: Value is not valid 上网找了半天也没找到答案,后来自己调试了一下。
  • 当数据提交时,是调用了CoalTransportStyleConverter的getAsObject说明这个对象已经创建起来了。但是为什么还报这个错误呢?
  • 于是我找了Messages_en.properties错误信息文件。
    Java代码 复制代码
    1. javax.faces.component.UISelectOne.INVALID={0}:ValidationError:Valueisnotvalid
    javax.faces.component.UISelectOne.INVALID={0}: Validation Error: Value is not valid
  • 又找到UISelectOne的validateValue方法。
    Java代码 复制代码
    1. protectedvoidvalidateValue(FacesContextcontext,Objectvalue){
    2. //Skipvalidationifitisnotnecessary
    3. super.validateValue(context,value);
    4. if(!isValid()||(value==null)){
    5. return;
    6. }
    7. //Ensurethatthevaluematchesoneoftheavailableoptions
    8. booleanfound=matchValue(value,newSelectItemsIterator(this));
    9. //Enqueueanerrormessageifaninvalidvaluewasspecified
    10. if(!found){
    11. FacesMessagemessage=
    12. MessageFactory.getMessage(context,INVALID_MESSAGE_ID,
    13. MessageFactory.getLabel(context,this));
    14. context.addMessage(getClientId(context),message);
    15. setValid(false);
    16. }
    17. }
    18. //---------------------------------------------------------PrivateMethods
    19. /**
    20. *<p>Return<code>true</code>ifthespecifiedvaluematchesoneofthe
    21. *availableoptions,performingarecursivesearchififa
    22. *{@linkSelectItemGroup}instanceisdetected.</p>
    23. *
    24. *@paramvalue{@linkUIComponent}valuetobetested
    25. *@paramitemsIteratoroverthe{@linkSelectItem}stobechecked
    26. */
    27. privatebooleanmatchValue(Objectvalue,Iteratoritems){
    28. while(items.hasNext()){
    29. SelectItemitem=(SelectItem)items.next();
    30. if(iteminstanceofSelectItemGroup){
    31. SelectItemsubitems[]=
    32. ((SelectItemGroup)item).getSelectItems();
    33. if((subitems!=null)&&(subitems.length>0)){
    34. if(matchValue(value,newArrayIterator(subitems))){
    35. return(true);
    36. }
    37. }
    38. }else{
    39. //Coercetheitemvaluetypebeforecomparingvalues.
    40. Classtype=value.getClass();
    41. ObjectnewValue;
    42. try{
    43. newValue=getFacesContext().getApplication().
    44. getExpressionFactory().coerceToType(item.getValue(),type);
    45. }catch(ELExceptionele){
    46. newValue=item.getValue();
    47. }catch(IllegalArgumentExceptioniae){
    48. //IfcoerceToTypefails,perthedocsitshouldthrow
    49. //anELException,however,GF9.0and9.0u1willthrow
    50. //anIllegalArgumentExceptioninstead(seeGFissue1527).
    51. newValue=item.getValue();
    52. }
    53. if(value.<SPANstyle="COLOR:#ff0000">equals</SPAN>
    54. (newValue)){
    55. return(true);
    56. }
    57. }
    58. }
    59. return(false);
    60. }
    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);
    
    
    
        }
    这里调用了equals方法,结果是不行,所以抛出了这个异常。
  • 重写CoalTransportStype的equals方法即可:
    Java代码 复制代码
    1. @Entity
    2. @Table(name="T_CoalTransportStyle")
    3. publicclassCoalTransportStyleimplementsSerializable{
    4. /**
    5. *
    6. */
    7. privatestaticfinallongserialVersionUID=-5090574246490412429L;
    8. privateLongid;
    9. privateStringparaName;
    10. @Id
    11. @GeneratedValue(strategy=GenerationType.AUTO)
    12. publicLonggetId(){
    13. returnid;
    14. }
    15. publicvoidsetId(Longid){
    16. this.id=id;
    17. }
    18. @Column(unique=true,nullable=false)
    19. publicStringgetParaName(){
    20. returnparaName;
    21. }
    22. publicvoidsetParaName(StringparaName){
    23. this.paraName=paraName;
    24. }
    25. publicbooleanequals(Objectobj){
    26. if(this==obj)
    27. returntrue;
    28. if(obj==null)
    29. returnfalse;
    30. if(getClass()!=obj.getClass())
    31. returnfalse;
    32. finalCoalTransportStyleother=(CoalTransportStyle)obj;
    33. if(id==null){
    34. if(other.id!=null)
    35. returnfalse;
    36. }elseif(!id.equals(other.id))
    37. returnfalse;
    38. if(paraName==null){
    39. if(other.paraName!=null)
    40. returnfalse;
    41. }elseif(!paraName.equals(other.paraName))
    42. returnfalse;
    43. returntrue;
    44. }
    45. }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值