我正在编写我的第一个 Java EE 6 Web 应用程序作为学习练习。我没有使用框架,只是 JPA 2.0、EJB 3.1 和 JSF 2.0。
我有一个自定义转换器将存储在 SelectOne 组件中的 JPA 实体转换回实体。我正在使用 InitialContext.lookup 来获取对 session Bean 的引用以查找相关实体。
我想创建一个通用实体转换器,因此我不必为每个实体创建一个转换器。我想我会创建一个抽象实体并让所有实体扩展它。然后为抽象实体创建一个自定义转换器并将其用作所有实体的转换器。
这听起来合理和/或可行吗?
没有一个抽象实体,只是一个转换任何实体的转换器会更有意义吗?在那种情况下,我不确定如何获得对适当 session Bean 的引用。
我已包含我当前的转换器,因为我不确定我是否以最有效的方式获得对我的 session Bean 的引用。
package com.mycom.rentalstore.converters;
import com.mycom.rentalstore.ejbs.ClassificationEJB;
import com.mycom.rentalstore.entities.Classification;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import javax.faces.convert.FacesConverter;
import javax.naming.InitialContext;
import javax.naming.NamingException;
@FacesConverter(forClass = Classification.class)
public class ClassificationConverter implements Converter {
private InitialContext ic;
private ClassificationEJB classificationEJB;
@Override
public Object getAsObject(FacesContext context, UIComponent component, String value) {
try {
ic = new InitialContext();
classificationEJB = (ClassificationEJB) ic.lookup("java:global/com.mycom.rentalstore_RentalStore_war_1.0-SNAPSHOT/ClassificationEJB");
} catch (NamingException e) {
throw new ConverterException(new FacesMessage(String.format("Cannot obtain InitialContext - %s", e)), e);
}
try {
return classificationEJB.getClassificationById(Long.valueOf(value));
} catch (Exception e) {
throw new ConverterException(new FacesMessage(String.format("Cannot convert %s to Classification - %s", value, e)), e);
}
}
@Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
return String.valueOf(((Classification) value).getId());
}
}
最佳答案
我正在使用 JSF 2.0 查看 map :
@FacesConverter("entityConverter")
public class EntityConverter implements Converter {
private static final String key = "com.example.jsf.EntityConverter";
private static final String empty = "";
private Map<String, Object> getViewMap(FacesContext context) {
Map<String, Object> viewMap = context.getViewRoot().getViewMap();
@SuppressWarnings({ "unchecked", "rawtypes" })
Map<String, Object> idMap = (Map) viewMap.get(key);
if (idMap == null) {
idMap = new HashMap<String, Object>();
viewMap.put(key, idMap);
}
return idMap;
}
@Override
public Object getAsObject(FacesContext context, UIComponent c, String value) {
if (value.isEmpty()) {
return null;
}
return getViewMap(context).get(value);
}
@Override
public String getAsString(FacesContext context, UIComponent c, Object value) {
if (value == null) {
return empty;
}
String id = ((Persistent) value).getId().toString();
getViewMap(context).put(id, value);
return id;
}
}
关于java - 通用 JSF 实体转换器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4268179/