日期:2014-05-17 浏览次数:20624 次
/**
* 通用取数据对象模板(entity:类名,需与实际名同,可指定包名package;其他属性名需与类属性名同,因为要调用相应的getter)
*
* @example <@vcms_entity entity="Channel" package="com.vcms.cms.entity" id="1">
* </@vcms_entity>
*
* @param entity
* 类名 必填 该类名大小写正确,例如有一个类是UserInfo,如果写成userInfo或Userinfo都是错误
*
* @param package 包名 选填 默认是com.vcms.cms.entity
*
* @param id
* 对象对应的id 必填
*
* @author vick
*
*/
@Component("vcms_entity")
public class VcmsEntityDirective implements TemplateDirectiveModel {
/**
* 结果集合
*/
private static final String RESULT = "obj";
private int id;
private BasicService basicService;
@SuppressWarnings("rawtypes")
@Override
public void execute(Environment env, Map params, TemplateModel[] loopVars,
TemplateDirectiveBody body) throws TemplateException, IOException {
Class<?> clazz = null; // 查找对象
TemplateModel className = null;
String packageName = null;
// 遍历Map
Iterator paramIter = params.entrySet().iterator();
Map.Entry ent;
String paramName;
TemplateModel paramValue;
while (paramIter.hasNext()) {
ent = (Map.Entry) paramIter.next();
paramName = (String) ent.getKey();
paramValue = (TemplateModel) ent.getValue();
// 处理"entity"
if ("entity".equals(paramName)) {
className = paramValue;
}
// 处理"package"
if ("package".equals(paramName)) {
packageName = paramValue.toString().trim();
}
// 处理Id
if ("id".equals(paramName)) {
id = FreeMarkertUtil.getNumberValue(paramName, paramValue)
.intValue();
}
}
/**
* 设置类
*/
if (null != packageName && !"".equals(packageName)) {
clazz = FreeMarkertUtil.findOutClass(className, packageName);
} else {
clazz = FreeMarkertUtil.findOutClass(className);
}
// 检查id
if (id < 1) {
throw new TemplateModelException(
"The \"id\" parameter is required.And the value of it should be larger than 0");
}
// 查询结果
Object obj = basicService.findById(clazz, id);
// // 找不到对象时,创建空对象
// if (null == obj) {
// try {
// obj = clazz.newInstance();
// } catch (Exception e) {