我有这个f:viewParam
,我尝试绑定 validate 并将 a 转换userId
为Player
,我得到了意想不到的结果。
<f:metadata>
<f:viewParam name="userId" value="#{myBean.selectedPlayer}" converter="pConverter"
converterMessage="Bad Request. Unknown User" required="true"
requiredMessage="Bad Request. Please use a link from within the system" />
</f:metadata>
<h:body>
<p:messages id="msgs"/>
<h:form>
<ul>
<li><a href="index2.xhtml?userId=1">Harry</a></li>
<li><a href="index2.xhtml?userId=2">Tom</a></li>
<li><a href="index2.xhtml?userId=3">Peter</a></li>
</ul>
</h:form>
<h:form>
<h:panelGrid columns="2" rendered="#{not empty myBean.selectedPlayer}">
<h:outputText value="Id: #{myBean.selectedPlayer.id}"/>
<h:outputText value="Name: #{myBean.selectedPlayer.name}"/>
</h:panelGrid>
</h:form>
<h:form id="testForm">
<h:inputText value="#{myBean.text}"/>
<p:commandButton value="Switch" update=":msgs testForm"/>
<h:outputText value="#{myBean.text}" rendered="#{not empty myBean.text}"/>
</h:form>
</h:body>
我的转换器看起来像这样
@FacesConverter(value="pConverter")
public class PConverter implements Converter {
private static final List<Player> playerList;
static{
playerList = new ArrayList<Player>();
playerList.add(new Player(1, "Harry"));
playerList.add(new Player(2, "Tom"));
playerList.add(new Player(3, "Peter"));
}
@Override
public Object getAsObject(FacesContext fc, UIComponent uic, String value) {
if(value == null || !value.matches("\\d+")){
return null;
}
long id = Long.parseLong(value);
for(Player p : playerList){
if(p.getId() == id){
return p;
}
}
throw new ConverterException(new FacesMessage("Unknown userId: " + value));
}
@Override
public String getAsString(FacesContext fc, UIComponent uic, Object value) {
if(!(value instanceof Player) || value == null){
return null;
}
return String.valueOf(((Player)value).getId());
}
}
当我单击三个链接(Harry、Tom、Peter)时,转换器工作得很好。它转换 id 并将player
回绑定到我的托管 bean。然后我在文本框中输入一些东西,然后单击Switch
,第一次它工作正常,我输入的内容出现在按钮旁边,但后来我更改了我输入的内容,Switch
再次单击,然后出现错误消息Bad Request. Please use a link from within the system
,这是错误消息为. required
_ f:viewParam
如果我把 f:viewParam 拿出来,那么一切正常。令人惊讶的是,如果我从 f:viewParam 切换到 o:viewParam (OmniFaces),那么效果很好。