自定义EL表达式输出Clob内容

做项目的时候遇到了一个问题,就是EL表达式无法输出Clob的内容,只是会把Clob的类型简单的打印一下,从网上搜了一下,找到解决方法就是自定义一个EL表达式函数,来输出Clob内容,
1.首先写一个函数,注意所有的函数都必须是静态的啊。
代码如下:
package com.mj.utils;

import java.io.IOException;
import java.io.Reader;
import java.sql.Clob;
import java.sql.SQLException;


/**
 * 自定义EL表达式输出Clob内容
 * @author M.J
 *
 */
public class El_Clob {
	//输出clob内容,方法必须为静态方法
	public static String printClob(Clob clob){
		StringBuffer strClob=new StringBuffer();
		String str="";
		try {
			Reader reader=clob.getCharacterStream();
			char[] buffer=new char[1024];
			int length=0;
			while((length=reader.read(buffer, 0, 1024))!=-1){
				strClob.append(buffer, 0, length);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		str=strClob.toString();
		return str;
	}
}

2.写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.0</tlib-version>
	 <short-name>myEL</short-name>
	<function>
		<description>将Clob转换成String对象</description>
		<name>printClob</name>
		<function-class>com.mj.utils.El_Clob</function-class>
		<function-signature>java.lang.String printClob(java.sql.Clob)</function-signature>
		<example>${myEL:printClob(clob)}</example>
	</function>
</taglib>

3.在JSP页面中引用
<%@ taglib uri="/WEB-INF/tlds/myEL.tld" prefix="myEL" %>

使用的时候,可以把Clob对象用<c:set/>标签设置到一个变量中,然后在引用这个变量
<td>
										<c:set value="${user.userDesc}" var="clob" scope="page"></c:set>
										${myEL:printClob(clob)}
</td>

你可能感兴趣的:(java,sql,jsp,Web,xml)