TB源码分析:StyleTag

类别:Java 点击:0 评论:0 推荐:
package com.terac.tags;

import com.terac.util.EncodingUtil;

import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.BodyContent;
import javax.servlet.jsp.tagext.BodyTagSupport;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StyleTag extends BodyTagSupport {
private int imageEnabled=1;

public void setImageEnabled(int imageEnabled) {
this.imageEnabled = imageEnabled;
}

public int doAfterBody() {
BodyContent bodyContent = getBodyContent();
String s = bodyContent.getString();
s = process(s);
JspWriter jspWriter = bodyContent.getEnclosingWriter();
try {
jspWriter.print(s);
} catch (IOException e) {
//
}
return EVAL_PAGE;
}

public static void main(String[] args) {
String s = new StyleTag().process("aaa");
System.out.println(s);
}

private String process(String s) {
//s = escapeXml(s);
s = convertNewLines(s);
s = EncodingUtil.ga(s);
s = convert(s, "\\[b\\](.[^\\[]*)(\\[\\/b\\])", "<b>$1</b>");
s = convert(s, "\\[i\\](.[^\\[]*)(\\[\\/i\\])", "<i>$1</i>");
s = convert(s, "\\[u\\](.[^\\[]*)(\\[\\/u\\])", "<u>$1</u>");
if(imageEnabled==1)
s = convert(s, "\\[img\\]http:\\/\\/(.[^\\[]*)\\[\\/img\\]", "<img src=\"http://$1\" border=\"0\" onload=\"if(this.width>screen.width*0.7) {this.resized=true; this.width=screen.width*0.7;} \" onmouseover=\"if(this.resized) this.style.cursor='hand';\" onclick=\"if(this.resized) {window.open('http://$1');}\">");
s = convert(s, "\\[url\\](.[^\\[]*)(\\[\\/url\\])", "<a href=\"$1\" target=_blank>$1</a>");
s = convert(s, "(\\[url=(.[^\\[]*)\\])(.[^\\[]*)(\\[\\/url\\])", "<a href=\"$2\" target=_blank>$3</a>");
s = EncodingUtil.ag(s);
return s;
}


private String convert(String source, String p, String r) {
Pattern pattern = Pattern.compile(p, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(source);
StringBuffer stringbuffer = new StringBuffer();
while (matcher.find()) {
matcher.appendReplacement(stringbuffer, r);
}
matcher.appendTail(stringbuffer);
return stringbuffer.toString();
}

private String convertNewLines(String param) {
String BRTag = "<br />";
StringBuffer sb = new StringBuffer("");
for (int i = 0; i < param.length(); i++) {
char c = param.charAt(i);
if (c == '\n') {
sb.append(BRTag);
} else if (c == '\r' && i < param.length() - 1 && param.charAt(i + 1) == '\n') {
sb.append(BRTag);
i++;
} else
sb.append(c);
}
return sb.toString();
}

}


本文地址:http://com.8s8s.com/it/it14729.htm