一个自定义模板标签解析方法

本文介绍了一种使用正则表达式和反射机制来自定义处理模板引擎中标签的方法,详细展示了如何解析并替换模板中的占位符,实现动态内容的填充。通过实例演示了如何读取列表数据,并将其应用到模板中。

好多时候用到模板功能,所以就需要自定义的标签处理,通常都是用正则表达式 当然我也不例外了

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;

import com.kuker.portal.entity.Archive;

public class TagParser {	

	private static final Pattern cmsList = Pattern.compile("<cms:list\\s(.*?)>(.*?)</cms:list>", Pattern.CASE_INSENSITIVE | Pattern.DOTALL);

	private String content = "你好啊<div><cms:list item=\"catalog\" count=\"10\"><li>${title}-${publishDate}</li></cms:list></div>你好<a href=''>asfdsafdsfds</a>"
			+ "<cms:list item=\"catalog\" count=\"2\"><li>${title}-${publishDate}</li></cms:list>";

	public static final Pattern pAttr1 = Pattern.compile("\\s*?(\\w+?)\\s*?=\\s*?(\\\"|\\')(.*?)\\2", 34);

	public static final Pattern pAttr2 = Pattern.compile("\\s*?(\\w+?)\\s*?=\\s*?([^\\'\\\"\\s]+)", 34);

	private static final Pattern pField = Pattern.compile("\\$\\{(\\w+?)\\.(\\w+?)(\\|(.*?))??\\}");
	
	private List<Archive> archiveList;
	
	public void init() {
		archiveList = new ArrayList<>();
		Archive archive = new Archive();
		archive.setTitle("xxx会见外国来宾");
		archive.setPublishDate("2018-09-09");
		archiveList.add(archive);
		
		Archive archive2 = new Archive();
		archive2.setTitle("ccc会见外国来宾");
		archive2.setPublishDate("2018-10-09");		
		archiveList.add(archive2);		
	}

	public void parseList()  {		
		init();
		Matcher m = cmsList.matcher(content);
		StringBuffer sb = new StringBuffer();
		int lastEndIndex = 0;
		int varIndex = 0;
		while (m.find(lastEndIndex)) {
			String jspContent;
			//取出文件原来内容
			sb.append(content.substring(lastEndIndex, m.start()));
			lastEndIndex = m.end();
			Map<String,Object> map = getAttrMap(m.group(1));
			String listContent = m.group(2);

			String item = ((String) map.get("item")).toLowerCase();
			String type = (String) map.get("type");
			String page = (String) map.get("page");
			String countStr = (String) map.get("count");
			String begin = (String) map.get("begin");
			String pagesizeStr = (String) map.get("pagesize");
			String var = (String) map.get("var");

			jspContent = "<!--循环-->";
			for (Archive archive :  archiveList) {
				jspContent += parsePlaceHolderStr(listContent,archive);
			}
			sb.append(jspContent);
			++varIndex;
		}
		sb.append(content.substring(lastEndIndex));
		content = sb.toString();
		System.out.println("----------->" + content);
	}
	
	/**
	 * 
	* @param str
	* @return Map<String,Object> 
	* @throws
	 */
	public  Map<String,Object> getAttrMap(String str) {
		String value;
		Map<String, Object> map = new HashMap<>();
		Matcher m = pAttr1.matcher(str);
		int lastEndIndex = 0;
		while (m.find(lastEndIndex)) {
			value = m.group(3);
			if (value != null) {
				value = value.trim();
			}
			map.put(m.group(1).toLowerCase(), value);
			lastEndIndex = m.end();
		}

		m = pAttr2.matcher(str);
		lastEndIndex = 0;
		while (m.find(lastEndIndex)) {
			value = m.group(2);
			if (value != null) {
				value = value.trim();
			}
			map.put(m.group(1).toLowerCase(), value);
			lastEndIndex = m.end();
		}
		return map;
	}
	
	public  Object getValue(Object obj, String fieldName) {
        if (obj == null || StringUtils.isEmpty(fieldName)) 
        	return null;
        try{
        	//获取对象的属性
        	Field field = obj.getClass().getDeclaredField(fieldName);
        	//对象的属性的访问权限设置为可访问
        	field.setAccessible(true);
        	//返回此属性的值
        	return field.get(obj);
        }catch(Exception ex) {
        	return null;
        }
    }

	public String parsePlaceHolderStr(String content,Archive archive) {
		StringBuffer sb = new StringBuffer();
		//sb.append("\"");
		Matcher m = pField.matcher(content);
		int lastEndIndex = 0;
		while (m.find(lastEndIndex)) {
			sb.append(content.substring(lastEndIndex, m.start()));
			String table = m.group(1);
			String field = m.group(2);

			if (table != null) {
				table = table.toLowerCase();
			}
			if (field != null) {
				field = field.toLowerCase();
			}
			sb.append(getValue(archive,field).toString());
			//sb.append("\"+" + table + ".getString(\"" + field + "\")+\"");
			lastEndIndex = m.end();
		}
		sb.append(content.substring(lastEndIndex));

		content = sb.toString();
		sb = new StringBuffer();
		m = Constant.PatternField.matcher(content);
		lastEndIndex = 0;
		while (m.find(lastEndIndex)) {
			sb.append(content.substring(lastEndIndex, m.start()));
			String field = m.group(1);
			//sb.append("\"+" + field + "+\"");
			sb.append(getValue(archive,field).toString());
			lastEndIndex = m.end();
		}
		sb.append(content.substring(lastEndIndex));
		return sb.toString();
	}

	public static void main(String[] args) {
		TagParser parse = new TagParser();
		parse.parseList();

	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值