探讨问题的同胞们可以加QQ群:315309006
不少人对CMS很好奇,觉得CMS系统中为什么会出现各种不一样的标签,诸如<foreach *>、#if,有一些是#getArticle("page=5")、更牛逼的还有“[循环][输出标题/][/循环]”,这些具体是怎么实现的呢?本文对CMS的核心内容进行实例解剖,帮助开发者理解CMS的工作原理、怎么设计自己的特殊标签。
一般来说一个完整的CMS系统,核心至少应该有这四部分:文档组织、文档发布、模板及自定义脚本、文件管理,其中模板及自定义脚本是最核心的部分,因为它要面对CMS的用户--这对做二次开发以网站制作为生的用户来说,易用是很重要的。
代码示例:(JAVA velocity实现) [或用freemark也行]
// 自定义声明
@Retention(RetentionPolicy.RUNTIME)
@Target( { ElementType.FIELD })
public @interface InjectProperty {
public String name();
public String defaultValue() default "";
}
}
// 描述注入对象
public class InjectBean {
@InjectProperty(name = "articleId")
private String articleId = "";
@InjectProperty(name = "title")
private String title = "";
@InjectProperty(name = "author")
private String author = "";
……
@InjectProperty(name = "cms")
private final INCCMSArticle cms = new INCCMSArticle(this);
……
}
// 将模板发布过程抽象成接口
public interface TemplateEngine {
// 发布模板
public String run(File f) throws Exception;
// 注入页面属性
public void injectProperty(Object param) ;
}
// 定义抽象类 处理执行过程
public abstract class AbstractTemplateEngine implements TemplateEngine {
private final Map<String, Object> properties = new HashMap<String, Object>();
public String run(File f) throws Exception {
return new VelocityTemplate().publishVelocityContent(properties, f);
}
public void injectProperty(Object param) throws InjectException {
for (Field f : param.getClass().getDeclaredFields()) {
InjectProperty injectProperty = f.getAnnotation(InjectProperty.class);
if (injectProperty == null) continue;
name = f.getName();
try {
Object value = PropertyUtils.getProperty(param, name);
properties.put(injectProperty.name(), value);
} catch (Exception e) {
throw new InjectException("加载[" + name + "]错误:" + e);
}
}
}
}
// 定义Velocity发布机
public class VelocityTemplate {
public String publishVelocityContent(Map properties, String forder,
String fileName) throws ParseErrorException,
MethodInvocationException, ResourceNotFoundException, IOException {
// filepath是模板位置
InputStream in = new FileInputStream(new File(#fiepath#));
Reader read = new InputStreamReader(in, "utf8");
VelocityEngine velocity = new VelocityEngine();
VelocityContext context = new VelocityContext(properties);
StringWriter sw = new StringWriter();
// 调用Velocity接口方法
velocity.evaluate(context, sw, null, in);
return sw.toString();
}
}

(上图是我实现的标签)
探讨问题的同胞们可以加QQ群:315309006
170

被折叠的 条评论
为什么被折叠?



