lan13217 发表于 2013-2-6 08:45:13

JSP EL 自定义函数

1.编写java类
ArticleUtil.JAVA
package com.wangyi.template;public class ArticleUtil {public static String addd(String s, int length) throws Exception{byte[] bytes = s.getBytes("Unicode");int n = 0; // 表示当前的字节数int i = 2; // 要截取的字节数,从第3个字节开始for (; i < bytes.length && n < length; i++){// 奇数位置,如3、5、7等,为UCS2编码中两个字节的第二个字节if (i % 2 == 1){n++; // 在UCS2第二个字节时n加1}else{// 当UCS2编码的第一个字节不等于0时,该UCS2字符为汉字,一个汉字算两个字节if (bytes != 0){n++;}}}// 如果i为奇数时,处理成偶数if (i % 2 == 1){// 该UCS2字符是汉字时,去掉这个截一半的汉字if (bytes != 0){i = i - 1;// 该UCS2字符是字母或数字,则保留该字符}else{i = i + 1;}}return new String(bytes, 0, i, "Unicode");}}
2.编写 wangyifunc.tag放置到WEB-INF下的任何子目录

<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>wangyi template taglib</description>    <tlib-version>1.0</tlib-version>    <short-name>wy</short-name>    <uri>http://template.wangyi.com/article/taglib</uri><function>      <description>Reverses the characters in the given String</description>      <name>add</name><function-class>com.wangyi.template.ArticleUtil</function-class><function-signature>java.lang.String addd( java.lang.String, int )</function-signature>    </function></taglib>
3编写jsp测试页面
<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%><%@ taglib prefix="wy" uri="http://template.wangyi.com/article/taglib"%><%request.setAttribute("aa","你好1你好2你好3你好4你好5你好6你好7你好8你好9你好0你好1你好2你好3你好4你好5你好6你好7你好8你好9你好0");//request.setAttribute("ints",new Integer(5));%>${wy:add(aa,32)}
页: [1]
查看完整版本: JSP EL 自定义函数