tw.com.javaworld.CH15.Filter (Java2HTML)

| Filter.java |

    1 package tw.com.javaworld.CH15;
    2
    3 import javax.servlet.*;
    4 import javax.servlet.jsp.*;
    5 import javax.servlet.jsp.tagext.*;
    6
    7 public class Filter extends BodyTagSupport {
    8
    9     public Filter() {
    10    }
    11
    12    public int doAfterBody() {
    13
    14        // 取得 body content 物件
    15        BodyContent bc = getBodyContent();
    16
    17        // 取得 request 物件
    18        ServletRequest request = pageContext.getRequest();
    19
    20        // 若得到 Filter 參數值為 Filter 時，將 body content 的內容傳入至 filter()
    21        // 否則，直接顯示原始資始內容
    22
    23        String filter;
    24
    25        if (request.getParameter("Filter") != null
    26            && request.getParameter("Filter").equals("Filter")) {
    27
    28            filter = toFilter(bc.getString());
    29        } else {
    30            filter = bc.getString();
    31        }
    32        try {
    33            JspWriter out = bc.getEnclosingWriter();
    34            out.print(filter);
    35        } catch (Exception e) {
    36            System.out.println("Error in FilterTag: " + e);
    37        }
    38        return (SKIP_BODY);
    39    }
    40
    41    //  主要將字串的內容中有以下特殊符號：< 、 > 、 " 、 &
    42    //  分別代替為 &lt; 、 &gt; 、 &quot; 、 &amp;
    43    public String toFilter(String input) {
    44        StringBuffer filtered = new StringBuffer(input.length());
    45        char c;
    46        for (int i = 0; i < input.length(); i++) {
    47            c = input.charAt(i);
    48            if (c == '<') {
    49                filtered.append("&lt;");
    50            } else if (c == '>') {
    51                filtered.append("&gt;");
    52            } else if (c == '"') {
    53                filtered.append("&quot;");
    54            } else if (c == '&') {
    55                filtered.append("&amp;");
    56            } else {
    57                filtered.append(c);
    58            }
    59        }
    60        return (filtered.toString());
    61    }
    62}