1. 程式人生 > >jsp自定義標籤的學習[從學習到工作(五)]

jsp自定義標籤的學習[從學習到工作(五)]

     在現在的開發平臺上發現有自己定義的標籤,於是在空閒時間學習了一下自定義標籤,並且做了一個簡單的ajax校驗的text標籤,廢話少說,看下面的步驟和程式碼。

     一. jsp頁面包含的內容

        

<%@taglib uri="http://com.zenglx.dream" prefix="my"%>
<!--由於用到了jquery的ajax方法所以引入jquery包-->
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery.min.js"></script>
<!-- validateClazz是校驗的自定義類,methdo的是定義的方法 -->
使用者名稱:<my:text id="ddddd" name="aaa" method="validate" validateClazz="com.test.tld.MyValidate"/>
使用者名稱2:<my:text validateClazz="com.test.tld.MyValidate2" name="cccc" method="validate" id="aaa"/>

   二.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">
    
  <description>myself </description>
  <display-name>mytest</display-name>
  <tlib-version>1.0</tlib-version>
  <short-name>my</short-name>
  <uri>http://com.zenglx.dream</uri>
  
  <tag>
  	<name>text</name>
  	<tag-class>com.test.tld.MyText</tag-class>
  	<body-content>empty</body-content>
  	<attribute>
  		<name>id</name>
  		<required>true</required>
  		<rtexprvalue>true</rtexprvalue>
  	</attribute>
  	<attribute>
  		<name>name</name>
  		<required>true</required>
  		<rtexprvalue>true</rtexprvalue>
  	</attribute>
  	<attribute>
  		<description>Custom method</description>
  		<name>method</name>
  		<required>true</required>
  		<rtexprvalue>true</rtexprvalue>
  	</attribute>
  	<attribute>
  	  <description>Custom class</description>
  		<name>validateClazz</name>
  		<required>true</required>
  		<rtexprvalue>true</rtexprvalue>
  	</attribute>
  </tag>
  </taglib>

    三.web.xml的配置

       

<jsp-config>
  	<taglib>
  		<taglib-uri>http://com.zenglx.dream</taglib-uri>
  		<taglib-location>/WEB-INF/tld/myTest.tld</taglib-location>
  	</taglib>
  </jsp-config>
  四.處理標籤java類的編寫

      

package com.test.tld;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspContext;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.SimpleTagSupport;

public class MyText extends SimpleTagSupport {
	private String id;
	private String name;
	private String method;
	private String validateClazz;

	public void setId(String id) {
		this.id = id;
	}

	public void setName(String name) {
		this.name = name;
	}

	public void setMethod(String method) {
		this.method = method;
	}

	public void setValidateClazz(String validateClazz) {
		this.validateClazz = validateClazz;
	}

	@Override
	public void doTag() throws JspException, IOException {

		JspContext jc = this.getJspContext();
		PageContext pc = (PageContext) jc;
		//String count = (String) pc.getAttribute("count");
		HttpServletRequest request = ((HttpServletRequest) pc.getRequest());
		//獲得專案路徑
		String path = request.getContextPath();
		
		//獲得專案在機器上的真是路徑
		//String realPath = pc.getServletContext().getRealPath("/");
		
		JspWriter jw = jc.getOut();
		
		jw.println("<input type='text' id='" + id + "' name='" + name
				+ "'/><span id='" + id + "s'></span>");
		jw.println("<br/>");
		
		jw.println("<script type='text/javascript'>");
		jw.println("$(function(){" + "$('#" + id + "').focus(function(){"
				+ "$('#" + id + "s').text('') " + "});" + "$('#" + id
				+ "').blur(function(){" + "var value=$('#" + id + "').val();"
				+ "$.ajax({" + "cache: false," + "async: true,"
				+ "type:'POST'," + "data: {textData: value,validateClazz:'"
				+ validateClazz + "',method:'" + method + "'}," + "url:'"
				+ path + "/validateData'," + "success: function(info) {"
				+ "   $('#" + id + "s').css('color','red');" + " 	$('#" + id
				+ "s').text(info);" + "}});" + "})});");
		jw.println("</script>");
		jw.flush();
	}

}
    五.校驗servlet的編寫,用到了反射機制完成方法的呼叫

       

package com.test.view;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ValidateDataServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		String value = request.getParameter("textData");
		String validateClazz = request.getParameter("validateClazz");
		String vlidateMethod = request.getParameter("method");
		try {
			//反射得到位元組碼檔案
			Class clazz = Class.forName(validateClazz);
			//得到自定義類
			Object o = clazz.newInstance();
			//得到自定義方法
			Method m = clazz.getMethod(vlidateMethod,String.class);
			//設定私有方法許可權
			m.setAccessible(true);
			//執行方法獲取返回值
			String info = (String) m.invoke(o, value);
			//將返回值寫入頁面
			response.getWriter().write(info);
			
		}catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		}
		
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doGet(request, response);
	}

}
  六.自己在標籤中定義的類和方法的編寫

    

package com.test.tld;

public class MyValidate  {

	public String validate(String value) {
		//自定義的java校驗類
		String info = null;
		if(null!=value&&("1234").equals(value)) {
			info = "恭喜你使用者名稱可用!";
		} else {
			info = "對不起,使用者名稱不可用";
		}
		return info;
	}

}

package com.test.tld;

public class MyValidate2  {

	public String validate(String value) {
		//自定義的java校驗類
		String info = null;
		if(null!=value&&("1111").equals(value)) {
			info = "恭喜你使用者名稱可用!";
		} else {
			info = "對不起,使用者名稱不可用";
		}
		return info;
	}

}