我发现视图参数不会从目标页面上支持 bean 不同的页面传递。如何将产品参数从 test1.xhtml 传递到 test2.xhtml?
测试.xhtml
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui" xmlns:o="http://omnifaces.org/ui">
<body>
<f:metadata>
<o:viewParam name="product" value="#{holder.value}"
converter="#{productConverter}"
converterMessage="Bad request. Unknown product." required="true"
requiredMessage="Bad request. Please use a link from within the system." />
</f:metadata>
<h:link outcome="/test2.xhtml" includeViewParams="true">link</h:link>
</body>
</html>
test2.xhtml
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui" xmlns:o="http://omnifaces.org/ui">
<h:head></h:head>
<body>
<f:metadata>
<o:viewParam name="product" value="#{holder2.value}"
converter="#{productConverter}"
converterMessage="Bad request. Unknown product." required="true"
requiredMessage="Bad request. Please use a link from within the system." />
</f:metadata>
<h:link outcome="/test.xhtml" includeViewParams="true">link</h:link>
</body>
</html>
持有人.java
@ManagedBean
@ViewScoped
public class Holder<T> implements Serializable {
private T value;
public T getValue() {
return value;
}
public void setValue(T value) {
this.value = value;
}
}
Holder2.java
@ManagedBean
@ViewScoped
public class Holder2<T> implements Serializable {
private T value;
public T getValue() {
return value;
}
public void setValue(T value) {
this.value = value;
}
}
产品.java
public class Product {
private String name;
public Product(String name) {
super();
this.name = name;
}
public String getName() {
return name;
}
}
产品转换器
public class ProductConverter implements Converter {
private Map<String,Product> productMap=new HashMap<String, Product>();
public ProductConverter(List<Product> products) {
for (Product product:products){
productMap.put(product.getName().toLowerCase(), product);
}
}
@Override
public Object getAsObject(FacesContext context, UIComponent component, String value) {
return productMap.get(value.toLowerCase());
}
@Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
if (!(value instanceof Product) ) {
return null;
}
return ((Product) value).getName().toLowerCase();
}
}