日期:2014-05-16 浏览次数:20348 次
? ? 近期做项目,使用JSTL对字符串进行编码,发现没有该函数来实现,无果情况下,只能自己DIY JSTL标签了,废话不多说,直接开始吧。
?
? ?首先编写一个类CommonUtil.java,里边放置了对字符串编码、解码的方法。保证方法必须是静态的public方法。?
?
package com.iteye.wangking717.util; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.net.URLEncoder; public class CommonUtil { public static String encoder(String source,String charset){ try { return URLEncoder.encode(source,charset); } catch (UnsupportedEncodingException e) { return ""; } } public static String decoder(String source,String charset){ try { return URLDecoder.decode(source,charset); } catch (UnsupportedEncodingException e) { return ""; } } }
? ?编写tld文件,建立一个文件,名称为lbs.tld,放在WEB-INF下面。?
?
<?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"> <description>Custom Functions</description> <tlib-version>1.0</tlib-version> <short-name>custom</short-name> <uri>/customFunction</uri> <function> <name>encoder</name> <function-class>com.iteye.wangking717.util.CommonUtil</function-class> <function-signature>java.lang.String encoder(java.lang.String,java.lang.String)</function-signature> <example>${custom.encoder('','')}</example> </function> <function> <name>decoder</name> <function-class>com.iteye.wangking717.util.CommonUtil</function-class> <function-signature>java.lang.String decoder(java.lang.String,java.lang.String)</function-signature> <example>${custom.decoder('','')}</example> </function> </taglib>?
? ?编写jsp页面,需要在头部指明引用的tld标签。?
?
<%@ taglib prefix="custom" uri="/customFunction" %> ${custom:encoder(username,'UTF-8')}?
?
?