通过截取字符串,保证英文和中文长度一致
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.util.Iterator;
import java.util.Map;
import junit.framework.Assert;
import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import freemarker.template.TemplateNumberModel;
import freemarker.template.TemplateScalarModel;
/**
* 截取字符串
* @author wy
*
*/
public class CutTemplateDirectiveModel implements TemplateDirectiveModel{
/**
* 截取字符串
*/
private static final String TEXT ="text";
/**
* 截取长度,默认为10
*/
private static final String LENGTH ="length";
/**
* 截取后+的字符串...
*/
private static final String EXT = "ext";
@SuppressWarnings({ "rawtypes", "unchecked" })
public void execute(Environment env, Map params, TemplateModel[] templateModels, TemplateDirectiveBody body) throws TemplateException, IOException {
Iterator<Map.Entry> paramIter = params.entrySet().iterator();
String text = null;
String ext="";
int length=10;
while (paramIter.hasNext()) {
Map.Entry ent = paramIter.next();
String paramName = (String) ent.getKey();
TemplateModel paramValue = (TemplateModel) ent.getValue();
if (paramName.equals(TEXT)) {
if (paramValue instanceof TemplateScalarModel) {
text = ((TemplateScalarModel) paramValue).getAsString();
}
else{
throw new RuntimeException("Value not String");
}
}
if (paramName.equals(LENGTH)) {
if (paramValue instanceof TemplateNumberModel) {
length = ((TemplateNumberModel) paramValue).getAsNumber().intValue();
}
else{
throw new RuntimeException("Length not int");
}
}
if (paramName.equals(EXT)) {
if (paramValue instanceof TemplateScalarModel) {
ext = ((TemplateScalarModel) paramValue).getAsString();
}
else{
throw new RuntimeException("Value not String");
}
}
}
Assert.assertNotNull(text);
if(body!=null){
Writer out = env.getOut();
out.append(subString(text, length, ext));
body.render(out);
}
else{
Writer out = env.getOut();
out.append(subString(text, length, ext));
}
}
private static String subString(String text, int length, String ext) {
int textLength = text.length();
int byteLength = 0;
StringBuffer returnStr = new StringBuffer();
for(int i = 0; i<textLength && byteLength < length*2; i++){
String str_i = text.substring(i, i+1);
if(str_i.getBytes().length == 1){//英文
byteLength++;
}else{//中文
byteLength += 2 ;
}
returnStr.append(str_i);
}
try {
if(byteLength<text.getBytes("GBK").length){//getBytes("GBK")每个汉字长2,getBytes("UTF-8")每个汉字长度为3
returnStr.append(ext);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return returnStr.toString();
}
}
然后在FTL模板头部写入
<#assign cut="com.cms.freemarker.CutTemplateDirectiveModel"?new()>
使用方法:<@cut text="CXCCCCCCC中文aaa" length=12 ext='...'/>
具体信息请查看:未解谜