JSP自定义标签之自动完成框

类一:
package com.globalzt.jsf.tags;

import javax.servlet.jsp.tagext.BodyTagSupport;

public abstract class AbstractUITag extends BodyTagSupport {
//属性
protected String cssClass;
    protected String cssStyle;
    protected String title;
    protected String disabled;
    protected String label;
    protected String name;
    protected String required;
    protected String tabindex;
    protected String value;
   
    //事件
    protected String onclick;
    protected String ondblclick;
    protected String onmousedown;
    protected String onmouseup;
    protected String onmouseover;
    protected String onmousemove;
    protected String onmouseout;
    protected String onfocus;
    protected String onblur;
    protected String onkeypress;
    protected String onkeydown;
    //protected String onkeyup;
    protected String onselect;
    protected String onchange;
   
public String getCssClass() {
return cssClass;
}
public void setCssClass(String cssClass) {
this.cssClass = cssClass;
}
public String getCssStyle() {
return cssStyle;
}
public void setCssStyle(String cssStyle) {
this.cssStyle = cssStyle;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDisabled() {
return disabled;
}
public void setDisabled(String disabled) {
this.disabled = disabled;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRequired() {
return required;
}
public void setRequired(String required) {
this.required = required;
}
public String getTabindex() {
return tabindex;
}
public void setTabindex(String tabindex) {
this.tabindex = tabindex;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getOnclick() {
return onclick;
}
public void setOnclick(String onclick) {
this.onclick = onclick;
}
public String getOndblclick() {
return ondblclick;
}
public void setOndblclick(String ondblclick) {
this.ondblclick = ondblclick;
}
public String getOnmousedown() {
return onmousedown;
}
public void setOnmousedown(String onmousedown) {
this.onmousedown = onmousedown;
}
public String getOnmouseup() {
return onmouseup;
}
public void setOnmouseup(String onmouseup) {
this.onmouseup = onmouseup;
}
public String getOnmouseover() {
return onmouseover;
}
public void setOnmouseover(String onmouseover) {
this.onmouseover = onmouseover;
}
public String getOnmousemove() {
return onmousemove;
}
public void setOnmousemove(String onmousemove) {
this.onmousemove = onmousemove;
}
public String getOnmouseout() {
return onmouseout;
}
public void setOnmouseout(String onmouseout) {
this.onmouseout = onmouseout;
}
public String getOnfocus() {
return onfocus;
}
public void setOnfocus(String onfocus) {
this.onfocus = onfocus;
}
public String getOnblur() {
return onblur;
}
public void setOnblur(String onblur) {
this.onblur = onblur;
}
public String getOnkeypress() {
return onkeypress;
}
public void setOnkeypress(String onkeypress) {
this.onkeypress = onkeypress;
}
public String getOnkeydown() {
return onkeydown;
}
public void setOnkeydown(String onkeydown) {
this.onkeydown = onkeydown;
}
public String getOnselect() {
return onselect;
}
public void setOnselect(String onselect) {
this.onselect = onselect;
}
public String getOnchange() {
return onchange;
}
public void setOnchange(String onchange) {
this.onchange = onchange;
}
}
类2:
package com.globalzt.jsf.tags;

import java.io.IOException; 
import javax.servlet.jsp.JspException;  
import javax.servlet.jsp.JspWriter;

public class AutoCompleteTextBoxTag extends AbstractUITag {


private static final long serialVersionUID = -2977156223449289185L;

private String width;            //宽度
private String minWords; //用户需要输入的最小字符数即可进行提示操作
private String contentCss; //提示DIV的样式
private String oncomplete;       //用户的回调函数
private String className;        //用户提供数据的类全名
private String methodName;       //用户提供数据的方法名
private StringBuilder rtnMessage;

public int doStartTag() throws JspException {
    return EVAL_BODY_INCLUDE; 
    }
   
    public int doEndTag() throws JspException{
    createUserControl();
    JspWriter writer=pageContext.getOut();
    try {
writer.write(rtnMessage.toString());
} catch (IOException e) {
e.printStackTrace();
}
    return EVAL_PAGE;
    }
    //在已经设置正文内容之后、但是对它进行判断之前调用doInitBody方法。一般用这个方法执行所有依赖于正文内容的初始化。
    public void doInitBody(){
   
    }
    //doAfterBody方法在判断了正文内容之后调用
    public int doAfterBody(){
    return 1;
    }
    /**
  * 创建用户自定义控件
  * 1.创建自动完成框控件
  * 2.为该控件定制用户属性
  * 3.创建提示信息DIV
  * 4.注册该控件所需的JS方法
  * @author 贾松帽
  * @data 2008-11-06
  */
    public void createUserControl(){
    rtnMessage=new StringBuilder();
    //1.创建自动完成框控件
    rtnMessage.append("<input type=\"text\" ");
    //2.为该控件定制用户属性
    rtnMessage.append(" id=\"globalztAutoCompleteBox\"");
    if(this.className!=null){
    rtnMessage.append(" className=\"");
    rtnMessage.append(this.className);
    rtnMessage.append("\"");
    }
    if(this.methodName!=null){
    rtnMessage.append(" methodName=\"");
    rtnMessage.append(this.methodName);
    rtnMessage.append("\"");
    }
    if(this.value!=null){
    rtnMessage.append(" value=\"");
    rtnMessage.append(this.value);
    rtnMessage.append("\"");
    }
    if(this.name!=null){
    rtnMessage.append(" name=\"");
    rtnMessage.append(this.name);
    rtnMessage.append("\"");
    }
    if(this.title!=null){
    rtnMessage.append(" title=\"");
    rtnMessage.append(this.title);
    rtnMessage.append("\"");
    }
    if(this.cssClass!=null){
    rtnMessage.append(" class=\"");
    rtnMessage.append(this.cssClass);
    rtnMessage.append("\"");
    }
    if(this.cssStyle!=null){
    rtnMessage.append(" style=\"");
    rtnMessage.append(this.cssStyle);
    rtnMessage.append("\"");
    }
    if(this.disabled!=null){
    rtnMessage.append(" disabled=\"");
    rtnMessage.append(this.disabled);
    rtnMessage.append("\"");
    }
    if(this.onclick!=null){
    rtnMessage.append(" onclick=\"");
    rtnMessage.append(this.onclick);
    rtnMessage.append("\"");
    }
    if(this.onblur!=null){
    rtnMessage.append(" onblur=\"");
    rtnMessage.append(this.onblur);
    rtnMessage.append("\"");
    }
    if(this.onchange!=null){
    rtnMessage.append(" onchange=\"");
    rtnMessage.append(this.onchange);
    rtnMessage.append("\"");
    }
    if(this.onfocus!=null){
    rtnMessage.append(" onfocus=\"");
    rtnMessage.append(this.onfocus);
    rtnMessage.append("\"");
    }
    if(this.onkeydown!=null){
    rtnMessage.append(" onkeydown=\"");
    rtnMessage.append(this.onkeydown);
    rtnMessage.append("\"");
    }
    if(this.onkeypress!=null){
    rtnMessage.append(" onkeypress=\"");
    rtnMessage.append(this.onkeypress);
    rtnMessage.append("\"");
    }
    if(this.minWords==null){
    rtnMessage.append(" minWords=\"");
rtnMessage.append(this.minWords);
System.out.println(this.minWords);
rtnMessage.append("\"");
    }
    if(this.width!=null){
    this.width=this.width.toLowerCase().replaceAll("px", "");
    rtnMessage.append(" width=\"");
    rtnMessage.append(this.width);
    rtnMessage.append("px\"");
    }
    rtnMessage.append(" onblur=\'setSuggestionsDivdispare(event);\'");
    rtnMessage.append(" onkeyup=\'");
    rtnMessage.append(getOnKeyUpEvent());
    rtnMessage.append("\'");
    rtnMessage.append("></input>");
    //3.创建提示信息DIV
    rtnMessage.append(getSuggestionsDiv());
    //4.注册该控件所需的JS方法
    rtnMessage.append(getSqlFunction());
    }
   
    /**
     * 为控件设置onkeyup事件,该事件是完成搜索功能的核心
* @author 贾松帽
* @data 2008-11-06
     */
    private String getOnKeyUpEvent(){
    StringBuilder keyUpSB=new StringBuilder();
    keyUpSB.append("$(\"#globalztSuggestionsDiv\").hide();");
    keyUpSB.append("if($(\"#globalztAutoCompleteBox\").val().length>=");
    keyUpSB.append(this.minWords);
    keyUpSB.append("){");
    keyUpSB.append("$.post(\"transfer.jsp\",{textValue:$(\"#globalztAutoCompleteBox\").val(),className:\"");
    keyUpSB.append(this.className);
    keyUpSB.append("\",method:\"");
    keyUpSB.append(this.methodName);
    keyUpSB.append("\"},function(xml){setResult(xml);");
    if(this.oncomplete!=null){
    keyUpSB.append(this.oncomplete);
    }
    keyUpSB.append("});");
    keyUpSB.append("}");
    System.out.println(keyUpSB.toString());
    return keyUpSB.toString();
    }
    /**
     * 创建提示信息DIV
* @author 贾松帽
* @data 2008-11-06
     */
    private String getSuggestionsDiv(){
    StringBuilder suggestionDiv=new StringBuilder();
    suggestionDiv.append("<div id=\"globalztSuggestionsDiv\"");
    if(this.contentCss!=null){
    suggestionDiv.append(" class=\"");
        suggestionDiv.append(this.contentCss);
        suggestionDiv.append("\"");
    }
    suggestionDiv.append(" style=\"border:1 solid black;display:none;border:2 solid silver;z-index:99;position:absolute;");
    suggestionDiv.append(" width:");
    suggestionDiv.append(this.width);
    suggestionDiv.append("px\"");
    suggestionDiv.append("></div>");
    return suggestionDiv.toString();
    }
    /**
     * 声明JS方法
* @author 贾松帽
* @data 2008-11-06
     */
    private String getSqlFunction(){
    StringBuilder sqlSB=new StringBuilder();
    sqlSB.append("<script>");
    sqlSB.append("var lastbgcolor;");
    //将服务器返回的列表填充到下拉提示框中
    sqlSB.append("function setResult(xml)");
    sqlSB.append("{");
    sqlSB.append(" $('#globalztSuggestionsDiv').html(\"\");");
    sqlSB.append(" $('#globalztSuggestionsDiv').append(xml);");
    sqlSB.append(" setSuggestionsDivPosition();");
    sqlSB.append(" $(\'#globalztSuggestionsDiv\').show('normal');");
    sqlSB.append("}");
    //表格行点击事件
    sqlSB.append("function onrowclick(row)");
    sqlSB.append("{");
    sqlSB.append(" $(\"#globalztAutoCompleteBox\").val($(row).find(\"td:first-child\").text());");
    sqlSB.append(" $(\"#globalztSuggestionsDiv\").hide();");
    sqlSB.append("}");
    //表格鼠标滑过事件
    sqlSB.append("function onrowmouseover(row)");
    sqlSB.append("{");
    sqlSB.append(" lastbgcolor = $(row).css(\"background-color\");");
    sqlSB.append(" $(row).css(\"background-color\",\"#C0C0C0\");");
    sqlSB.append(" $(row).css(\"cursor\",\"pointer\");");
    sqlSB.append("}");
    //表格鼠标离开事件
    sqlSB.append("function onrowmouseout(row)");
    sqlSB.append("{");
    sqlSB.append(" $(row).css(\"background-color\",lastbgcolor)");
    sqlSB.append("}");
    //
    sqlSB.append("function setmousemove()");
    sqlSB.append("{");
    sqlSB.append(" evt=document.onmousemove;");
    sqlSB.append("}");
    //搜索框失去焦点事件
    sqlSB.append("function setSuggestionsDivdispare(evt)");
    sqlSB.append("{");
    sqlSB.append(" evt=evt||window.event;");
    sqlSB.append(" var div = document.getElementById(\"globalztSuggestionsDiv\");");
    sqlSB.append(" var divRect=div.getBoundingClientRect();");
    sqlSB.append(" var left=divRect.left;");
    sqlSB.append(" var right=divRect.right;");
    sqlSB.append(" var top=divRect.top;");
    sqlSB.append(" var bottom=divRect.bottom;");
    sqlSB.append(" var x,y;");
    sqlSB.append(" if(evt.pageX || evt.pageY)");
    sqlSB.append(" {");
    sqlSB.append(" x=evt.pageX;");
    sqlSB.append(" y=evt.pageY;");
    sqlSB.append(" }");
    sqlSB.append(" else");
    sqlSB.append(" {");
    sqlSB.append(" x=evt.clientX + document.body.scrollLeft - document.body.clientLeft;");
    sqlSB.append(" y=evt.clientY + document.body.scrollTop  - document.body.clientTop;");
    sqlSB.append(" }");
    sqlSB.append(" if(left>x || right<x || top>y || bottom<y)");
    sqlSB.append(" {$(\"#globalztSuggestionsDiv\").hide();}");
    sqlSB.append("}");
    //设置下拉列表框的位置
    sqlSB.append("function setSuggestionsDivPosition()");
    sqlSB.append("{");
    sqlSB.append(" var textBox = document.getElementById(\"globalztAutoCompleteBox\");");
    sqlSB.append(" var textBoxRect=textBox.getBoundingClientRect();");
    sqlSB.append(" var x=textBoxRect.left;");
    sqlSB.append(" var y=textBoxRect.top;");
    sqlSB.append(" var width=$(textBox).css(\"width\");");
    sqlSB.append(" width=Number(width.replace(\"px\",\"\"))+6;");
    sqlSB.append(" var left=x-2;");
    sqlSB.append(" var top=y+textBox.offsetHeight-2;");
    sqlSB.append(" $(\"#globalztSuggestionsDiv\").css(\"top\",top);");
    sqlSB.append(" $(\"#globalztSuggestionsDiv\").css(\"left\",left);");
    sqlSB.append(" $(\"#globalztSuggestionsDiv\").css(\"width\",width);");
    sqlSB.append("}");
    sqlSB.append("</script>");
    sqlSB.append("<style type=\"text/css\">");
    sqlSB.append(".tableborder{border:0px;}");
    sqlSB.append("</style>");
    return sqlSB.toString();
    }

public String getContentCss() {
return contentCss;
}

public void setContentCss(String contentCss) {
this.contentCss = contentCss;


public String getOncomplete() {
return oncomplete;
}

public void setOncomplete(String oncomplete) {
this.oncomplete = oncomplete;
}

public String getClassName() {
return className;
}

public void setClassName(String className) {
this.className = className;
}

public String getMethodName() {
return methodName;
}

public void setMethodName(String methodName) {
this.methodName = methodName;
}

public String getWidth() {
return width;
}

public void setWidth(String width) {
this.width = width;
}

public String getMinWords() {
return minWords;
}

public void setMinWords(String minWords) {
this.minWords = minWords;
}
}
类3:
package com.globalzt.jsf.tags;

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;

public class LoadMethod {
/**
* 加载某指定类的指定方法
* @param cName
* @param MethodName
* @param type
* @param param
* @return Object
* @author 贾松帽
*/
@SuppressWarnings("unchecked")
public Object Load(String cName, String MethodName, String[] type,String[] param) {
Object retobj = null;
try {
// 加载指定的Java类
Class cls = Class.forName(cName);

// 获取指定对象的实例
Constructor ct = cls.getConstructor(null);
Object obj = ct.newInstance(null);

// 构建方法参数的数据类型
Class partypes[] = this.getMethodClass(type);

// 在指定类中获取指定的方法
Method meth = cls.getMethod(MethodName, partypes);

// 构建方法的参数值
Object arglist[] = this.getMethodObject(type, param);

// 调用指定的方法并获取返回值为Object类型
retobj = meth.invoke(obj, arglist);

} catch (Throwable e) {
System.err.println(e);
}
return retobj;
}

// 获取参数类型 Class[]的方法
@SuppressWarnings("unchecked")
public Class[] getMethodClass(String[] type) {
Class[] cs = new Class[type.length];
for (int i = 0; i < cs.length; i++) {
if (!type[i].trim().equals("") || type[i] != null) {
if (type[i].equals("int") || type[i].equals("Integer")) {
cs[i] = Integer.TYPE;
} else if (type[i].equals("float") || type[i].equals("Float")) {
cs[i] = Float.TYPE;
} else if (type[i].equals("double") || type[i].equals("Double")) {
cs[i] = Double.TYPE;
} else if (type[i].equals("boolean")
|| type[i].equals("Boolean")) {
cs[i] = Boolean.TYPE;
} else {
cs[i] = String.class;
}
}
}
return cs;
}

// 获取参数 Object[]的方法
public Object[] getMethodObject(String[] type, String[] param) {
Object[] obj = new Object[param.length];
for (int i = 0; i < obj.length; i++) {
if (!param[i].trim().equals("") || param[i] != null) {
if (type[i].equals("int") || type[i].equals("Integer")) {
obj[i] = new Integer(param[i]);
} else if (type[i].equals("float") || type[i].equals("Float")) {
obj[i] = new Float(param[i]);
} else if (type[i].equals("double") || type[i].equals("Double")) {
obj[i] = new Double(param[i]);
} else if (type[i].equals("boolean")
|| type[i].equals("Boolean")) {
obj[i] = new Boolean(param[i]);
} else {
obj[i] = param[i];
}
}
}
return obj;
}
}
JSP文件:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"
    import="com.globalzt.jsf.test.SearchTest"
    import="java.util.*"
    import="com.globalzt.jsf.tags.*"
   
    %>
<%
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html");

out.clear();

String value=request.getParameter("textValue");
String className=request.getParameter("className");
String methodName=request.getParameter("method");

System.out.println(value);
System.out.println(className);
System.out.println(methodName);

out.print("<table id=\"globalzttable\" width=\"100%\" class=\"tableborder\" cellspacing=\"0\" style=\"border:1px solid black;background:white;margin:0;padding:0;\">");

LoadMethod loadMethod=new LoadMethod();
List<Object> list = (List<Object>) loadMethod.Load(className, methodName, new String[]{"String"},new String[]{value});


Object[] rows=list.toArray();
for(int i=0;i<rows.length;i++){
Object[] cols=(Object[])rows[i];
if(i%2==0){
out.print("\t<tr onclick=\"onrowclick(this)\" onmouseover=\"onrowmouseover(this)\" onmouseout=\"onrowmouseout(this)\">\n");
if(cols.length==1){
out.print("\t\t<td>"+cols[0]+"</div>\n");
}
else if(cols.length==2){
out.print("\t\t<td style=\"float:left;width:79%;\">"+cols[0]+"</td>\n");
out.print("\t\t<td style=\"text-align:right;width:79%;\">"+cols[1]+"</td>\n");
}
out.print("\t</tr>\n");
}
else{
out.print("\t<tr onclick=\"onrowclick(this)\" onmouseover=\"onrowmouseover(this)\" onmouseout=\"onrowmouseout(this)\">\n");
if(cols.length==1){
out.print("\t\t<td>"+cols[0]+"</td>\n");
}
else if(cols.length==2){
out.print("\t\t<td style=\"float:leftwidth:79%;\">"+cols[0]+"</td>\n");
out.print("\t\t<td style=\"text-align:right;width:20%;\">"+cols[1]+"</td>\n");
}
out.print("\t</tr>\n");
}

}

out.print("</table>");

%>
tld文件:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
"http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">  
<taglib>
<!-- 标签库的版本 -->
    <tlib-version>1.0</tlib-version>
    <!-- 这个标签库要求的JSP规范版本 -->
    <jsp-version>1.2</jsp-version>
    <!-- JSP页面编写工具可以用来创建助记名的可选名字 prefix -->
    <short-name>gzt</short-name>
    <!-- globalzt:搜索框控件 -->
    <tag>
<!-- 唯一标签名 -->
        <name>autoCompleteTextBox</name>
        <!-- 标签searchTextBox类的完全限定名 -->
        <tag-class>com.globalzt.jsf.tags.AutoCompleteTextBoxTag</tag-class>
        <!-- 正文内容类型 -->
        <body-content>jsp</body-content>
        <description>ajax search textbox</description>
        <!-- 属性 -->
        <attribute>
        <name>id</name>
        <required>false</required>
        </attribute>
        <attribute>
        <name>minWords</name>
        <required>true</required>
        </attribute>
        <attribute>
        <name>width</name>
        <required>false</required>
        </attribute>
        <attribute>
        <name>title</name>
        <required>false</required>
        </attribute>
        <attribute>
        <name>disabled</name>
        <required>false</required>
        </attribute>
        <attribute>
        <name>name</name>
        <required>false</required>
        </attribute>
        <attribute>
        <name>value</name>
        <required>false</required>
        </attribute>
       
        <attribute>
        <name>cssClass</name>
        <required>false</required>
        </attribute>
        <attribute>
        <name>cssStyle</name>
        <required>false</required>
        </attribute>
        <attribute>
        <name>title</name>
        <required>false</required>
        </attribute>
        <attribute>
        <name>disabled</name>
        <required>false</required>
        </attribute>
        <attribute>
        <name>contentCss</name>
        <required>false</required>
        </attribute>
        <attribute>
        <name>className</name>
        <required>true</required>
        </attribute>
        <attribute>
        <name>methodName</name>
        <required>true</required>
        </attribute>
        <!-- 事件 -->
        <attribute>
        <name>onclick</name>
        <required>false</required>
        </attribute>
        <attribute>
        <name>onfocus</name>
        <required>false</required>
        </attribute>
        <attribute>
        <name>onkeypress</name>
        <required>false</required>
        </attribute>
        <attribute>
        <name>onkeydown</name>
        <required>false</required>
        </attribute>
        <attribute>
        <name>onselect</name>
        <required>false</required>
        </attribute>
        <attribute>
        <name>onchange</name>
        <required>false</required>
        </attribute>
    </tag>
</taglib>

JSP页面使用范例:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="UTF-8"%>
<%@ taglib uri="/WEB-INF/tld/globalztTags.tld" prefix="gzt" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<style type="text/css">
.divcss{text-align:left;font-size:8px;}
</style>
<script src="js/jquery-latest.js" type=text/javascript></script>

<script type="text/javascript">

</script>
</head>
<body>

<div ></div>
<table style="border:2px solid silver;">
<tr>
<td>title1</td>
<td>title2</td>
<td>title3</td>
</tr>
<tr>
<td>goods name:</td>
<td>
<gzt:autoCompleteTextBox value="" id="stb1" minWords="2" width="800" contentCss="divcss"
cssStyle="width:250px" className="com.globalzt.jsf.test.SearchTest" methodName="doSearch"
name="searchContent1" title="search"></gzt:autoCompleteTextBox>
</td>

<td><input type="button" value="search"></input></td>
</tr>
<tr>
<td>footer1</td>
<td>footer2</td>
<td>footer3</td>
</tr>
</table>
</body>
</html>

你可能感兴趣的:(jsp,xml,css,servlet,JSF)