2010年11月7日 星期日

自訂編碼標籤範例

如果不將Eclipse的環境編碼改成UTF-8,似乎轉碼會有問題
因應這種情況寫了自訂標籤來協助處理

encrypt.tld=========

<?xml version="1.0" encoding="UTF-8" ?>
<taglib xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
    version="2.0">

    <tlib-version>1.2</tlib-version>            
    <short-name>encryptlib</short-name>    
    <uri>encrypt-tags</uri>                              
    <tag>
      <description>URL  get/post encrypting</description>
      <name>encrypt</name>
      <tag-class>tw.vencs.EncrptTag</tag-class>
      <body-content>empty</body-content>
    
      <attribute>
          <name>encryptValue</name>
          <required>true</required>
          <rtexprvalue>true</rtexprvalue>
      </attribute>
    </tag>

</taglib>

EncrptTag.java===============

package tw.vencs;

import javax.servlet.jsp.tagext.SimpleTagSupport;
import javax.servlet.jsp.JspException;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

public class EncrptTag extends SimpleTagSupport{
    private String encryptValue; 
   
    public void doTag() throws JspException { 
        try { 
            encryptValue = new String(encryptValue.getBytes("iso-8859-1"),"UTF-8"); 
            getJspContext().getOut().write(encryptValue);
        } catch (IOException e) { 
              Logger.getLogger(EncrptTag.class.getName()).log(Level.SEVERE, null, e);
              throw new RuntimeException();
        }    
    } 
    public void setEncryptValue(String encryptValue) { 
        this.encryptValue = encryptValue; 
    } 
}

Demo.jsp===============

.....
<%@ taglib prefix="e" uri="encrypt-tags" %>
.....
<body>
.....
....=<e:encrypt  encryptValue="${param.itemName}"/>
</body>
.....

沒有留言:

張貼留言