【发布时间】:2013-06-26 00:59:30
【问题描述】:
我正在尝试转换从另一个视图传递的 GET 请求参数,如下所示:
<f:metadata>
<f:viewParam name="id"
value="#{targetViewBean.fooFromSourceView}"
converter="fooConverter"
converterMessage="Foo converter message"
required="true" requiredMessage="Foo required message"/>
<f:viewAction action="#{targetViewBean.doSomethingWithFoo()}"/>
</f:metadata>
但是只有Converter.getAsString(..., Object value)方法被调用并且value总是为空,即使你真的发送了GET参数。
我找到了BalusC blog post about this,并且,AFAIK,我一直遵循它。还是不行。完整代码如下:
源视图
<h:head>
<title>Source view</title>
</h:head>
<h:body>
<ul>
<ui:repeat value="#{sourceViewBean.foos}" var="foo">
<li>
<h:link value="Foo \##{foo.id}" outcome="target-view">
<f:param name="id" value="#{foo.id}" />
</h:link>
</li>
</ui:repeat>
</ul>
</h:body>
支持豆
@Named @ViewScoped
public class SourceViewBean implements Serializable {
public Collection<Foo> getFoos() {
return Db.INSTANCE.getFoos();
}
private static final long serialVersionUID = 1L;
}
目标视图
<f:metadata>
<f:viewParam name="id"
value="#{targetViewBean.fooFromSourceView}"
converter="fooConverter"
converterMessage="Foo converter message"
required="true" requiredMessage="Foo required message"/>
<f:viewAction action="#{targetViewBean.doSomethingWithFoo()}"/>
</f:metadata>
<h:head>
<title>Target view</title>
</h:head>
<h:body>
<h:outputText value="ID: #{targetViewBean.fooFromSourceView.id}" />
</h:body>
目标视图支持 bean
@Named
@ViewScoped
public class TargetViewBean implements Serializable {
private Foo fooFromSourceView;
public void doSomethingWithFoo() {
System.out.println("Foo is here? " + fooFromSourceView != null);
}
public Foo getFooFromSourceView() {
return fooFromSourceView;
}
public void setFooFromSourceView(Foo fooFromSourceView) {
this.fooFromSourceView = fooFromSourceView;
}
private static final long serialVersionUID = 1L;
}
转换器
@FacesConverter(value = "fooConverter")
public class FooConverter implements Converter {
@Override
public Object getAsObject(
FacesContext context, UIComponent component, String value) {
if (value == null || !value.matches("\\d+")) {
return null;
}
for (Foo foo : Db.INSTANCE.getFoos()) {
if (foo.getId().equals(Integer.parseInt(value))) {
return foo;
}
}
throw new ConverterException(new FacesMessage("No Foo found!"));
}
@Override
public String getAsString(
FacesContext context, UIComponent component, Object value) {
if (!(value instanceof Foo) || ((Foo) value).getId() == null) {
return null;
}
return ((Foo) value).getId().toString();
}
}
【问题讨论】:
-
如果值为 null ,你怎么知道参数正在被发送?我尝试运行示例代码,它对我来说运行良好。唯一的区别是我将
Db.INSTANCE.getFoos();更改为List<Foo>,而doSomethingWithFoo()正在输出true。你确定它不在其他地方吗? -
GET 请求包含具有适当值的
id参数。由于getAsStringvalue为空,doSomethingWithFoo()永远不会被调用。可能是别的东西,但我不知道是什么。代码来自 NetBeans 7.3.1 中一个全新的 Java EE 7 maven 企业应用程序项目。 -
嗯...我假设
outputText只是显示ID -
好的,让我仔细检查一下我的工作。
-
我刚刚在转换器端进行了检查,
id请求参数确实存在。顺便说一句,在启动 glassfish 时会抛出 2 条消息,但我认为它与Class 'javax.ejb.PostActivate' not found, interception based on it is not enabled无关,而javax.ejb.PrePassivate的消息相同。
标签: jsf viewparams jsf-2.2 java-ee-7