我正在尝试转换inputText
为java.net.URL
JSF页面:
...
<h:form>
<h:inputText value="${myBean.url}" />
<h:commandButton type="submit" value="go" />
</h:form>
...
Run Code Online (Sandbox Code Playgroud)
我支持的bean是:
import java.net.URL;
@ManagedBean public class MyBean {
public URL url;
}
Run Code Online (Sandbox Code Playgroud)
我应该从头开始实现转换器还是有其他方法?
是的,你需要实现一个Converter
.这个特殊情况并不难:
@FacesConverter(forClass=URL.class)
public class URLConverter implements Converter {
@Override
public Object getAsObject(FacesContext context, UIComponent component, String value) {
if (value == null) {
return null;
}
try {
return new URL(value);
}
catch (MalformedURLException e) {
throw new ConverterException(new FacesMessage(String.format("Cannot convert %s to URL", value)), e);
}
}
@Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
if (value == null) {
return "";
}
return value.toString();
}
}
Run Code Online (Sandbox Code Playgroud)
把它放在项目的某个地方.由于@FacesConverter
它将自动注册自己.
归档时间: |
|
查看次数: |
2125 次 |
最近记录: |