ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • JSP(사용자 정의 태그 만들기)
    JSP 2020. 6. 17. 11:05

    JSP(사용자 정의 태그 만들기)

    사용자 정의 태그 작성을 위해 활용되는 자원


    1. 사용자 정의 태그는 특정 클래스 메서드를 대상으로 작성하고 활용


       메서드 선언시 반환타입과 파라미터 타입은 반드시 WrapperClass타입이여야 함


       ex) int (x) -> integer (o)


    2. 메서드 접근 지정자는 반드시 public 이고, static 선언과 동반되어야 함.

     

    [CustomTargetClass.java]

    package kr.or.ddit.utiles;
    
    import java.text.SimpleDateFormat;
    import java.util.Date;
    
    public class CustomTargetClass {
    	
    	public CustomTargetClass() {
    		
    	}
    	
    	public CustomTargetClass(int i) {
    		
    	}
    
    	public static Integer plus(Integer i, Integer j) {
    		return i + j;
    	}
    
    	public static Integer multiple(String i, Integer j) {
    		return Integer.parseInt(i) * j;
    	}
    
    	public static String today() {
    		SimpleDateFormat dateFormat = new SimpleDateFormat("YYYY/MM/DD");
    		return dateFormat.format(new Date());
    	}
    
    	public static Integer charCount(String target, String delim){
    		int idx = 0;
    		int cnt = 0;
    		
    		// "1234561" 중에 "1"은 몇번 포함되어 있는지
    		idx = target.indexOf(delim);
    		  for(; idx != -1; cnt++){
    		         target = target.substring(target.indexOf(delim)+1,target.length());
    		         idx = target.indexOf(delim);
    		      }
    		      return cnt;
    
    	}
    }
    

     

    애플리케이션 실행 시 다양한 클래스 로더가 다양한 시점에 해당 애플리케이션을 구성하는 자원들을

     

    메모리에 상주시킴

     

    - 클래스 로더

    //				ExtClassLoader				ApplicationClassLoader		subAppClassLoader					ServletContainerClassLoader
    
    
    // Standalone		JDK인스톨폴더/jre/lib/rt.jar	build path 하위 **.*.class		import로 활용되는 jar 내 **.*.class		
    
    // 	
    
    // Web			JDK인스톨폴더/jre/lib/rt.jar	build path 하위 **.*.class		import로 활용되는 jar 내 **.*.class		Servlet Class, jsp 호출 -> Servlet Class 로딩.
    
    //
    
    // 사용자 정의 태그 : *.tld
    
    // tld 파일 위치 : WEB-INF/ 하위
    
    // Class.forName("oracle.jdbc.driver.OracleDriver"); // -> subAppClassLoader에서 실행 (ojdbc6.jar)

    [customTagGenerator.jsp]

    <%@page import="java.io.File"%>
    <%@page import="java.io.FileWriter"%>
    <%@page import="java.io.IOException"%>
    <%@page import="java.io.BufferedWriter"%>
    <%@page import="java.lang.reflect.Method"%>
    <%@page import="java.lang.reflect.Constructor"%>
    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <%
    	Class targetClass =Class.forName("kr.or.ddit.utiles.CustomTargetClass"); 
        
          * targetClass = class kr.or.ddit.uiles.CustomTargetClass 값을 찾음
    	
    	//Constructor[] constructor = targetClass.getConstructor();
        
    	Constructor constructor = targetClass.getConstructor();
        
           * constructor = public kr.or.ddit.utiles.CustomTargetClass() 얻음
           
              생성자를 얻는건가? 아니면 해당 클래스?
              
        
    	Object instanceClass = constructor.newInstance();
        
           * 얻어온거를 인스턴스화?
    	
    	//targetClass.getName() -> kr.or.ddit.utiles.CustomTargetClass
        
    	// CustomeTargetClass 취득
    	
    	String className = targetClass.getName().substring(targetClass.getName().lastIndexOf(".")+1);
        
           * className = CustomTargetClass
    	
    	String declareStart = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?> \n" +
        	        "<taglib xmlns=\"http://java.sun.com/xml/ns/j2ee\" \n" + 
                    "\t\txmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" \n" +
                    "\t\txsi:schemaLocation=\"http://java.sun.com/xml/ns/j2ee \n" +
                    "\t\thttp://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd\" \n" +
                    "\t\tversion=\"2.0\"> \n" +
                    "\t<tlib-version>1.0</tlib-version>\n" +
                    "\t<short-name>" + className.toLowerCase() + "</short-name>\n" +
                    "\t<uri>http://www.bagrant.com/taglib/" + className.toLowerCase() + "-taglib</uri>\n";
                    
                    
                    * declareStart = <?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>customtargetclass</short-name>
    								<uri>http://www.bagrant.com/taglib/customtargetclass-taglib</uri>
    
                    
    	String declareContent = "";
        
    	String declareEnd = "</taglib>";
    	
    	
    	// 메소드  취득
        
    	// targetClass.getMethod("plus", Integet.class, Integet.class);
        
    	//						메소드명, 해당 메소드의 인자타입
    	
    	// 전체 메소드 취득
        
    	Method[] methods = targetClass.getMethods();
    	
    	
    	String temp = "";
    	
    	//object로부터 상속받은 메소드들을 걸러내기 위해
        
    	String extendsObjectMethods = "clone equals finalize getClass hashCode notify notifyAll toString wait";
    	
    	for(Method method : methods){
        
    		// Object로부터 상속받지 않은 메소드들만 가져올거
            
    		if(!extendsObjectMethods.contains(method.getName())){
            
    			//public static Integer plus(Integer i, Integer j){
                
    // 				return i+	
    // 			}
    
    			Class[] params = method.getParameterTypes();
    			
    			//java.lang.Integer " " + plus(
                
    			String methodSignature = method.getReturnType().getName() +
    									 " " + 
    									 method.getName() +
    									 "(";
                                         
    			int paramCnt =1;
                
    			for(Class param : params){
                
    				// for문 첫번째
                    
    				//java.lang.Integer " " + plus(java.lang.Integer
    						
    				// for문 두번째
                    
    				//java.lang.Integer " " + plus(java.lang.Integer, java.lang.Integer						
                    
    				methodSignature += param.getName();
                    
    				if(paramCnt++ < params.length){
                    
    					//java.lang.Integer " " + plus(java.lang.Integer,
                        
    					methodSignature += ", ";
    				}
    			}
                
    			//java.lang.Integer " " + plus(java.lang.Integer, java.lang.Integer)
                
    			methodSignature += ")";
    					
    			declareContent += "\t<function>\n" +
    							  			"\t\t<description>" + method.getName() + "의 활용</description>\n" +
    							  			"\t\t<name>" + method.getName() + "</name>\n" +
    							  			"\t\t<function-class>" + targetClass.getName() + "</function-class>\n" +
    							  			"\t\t<function-signature>" + methodSignature + "</function-signature>\n" +
    							  			"\t\t<example>\n" +
    							  				"\t\t\t<![CDATA[\n"+
    							  					"\t\t\t\t${" + className.toLowerCase()+":" + 
    							  								   methodSignature.substring(methodSignature.indexOf(" ")+1) +
    							  							  "}\n" +
    							  				"\t\t\t]]>\n" +
    							  			"\t\t</example>\n" +
    							  "\t</function>\n";
                                  
                                  
                       * declareContent = 	<function>
    										<description>charCount의 활용</description>
    										<name>charCount</name>
    										<function-class>kr.or.ddit.utiles.CustomTargetClass</function-class>
    										<function-signature>java.lang.Integer charCount(java.lang.String, java.lang.String)</function-signature>
    										<example>
    										<![CDATA[
    											${customtargetclass:charCount(java.lang.String, java.lang.String)}
    												]]>
    										</example>
    										</function>
    		<function>
    		<description>plus의 활용</description>
    		<name>plus</name>
    		<function-class>kr.or.ddit.utiles.CustomTargetClass</function-class>
    		<function-signature>java.lang.Integer plus(java.lang.Integer, java.lang.Integer)</function-signature>
    		<example>
    			<![CDATA[
    				${customtargetclass:plus(java.lang.Integer, java.lang.Integer)}
    			]]>
    		</example>
    	</function>
    	<function>
    		<description>today의 활용</description>
    		<name>today</name>
    		<function-class>kr.or.ddit.utiles.CustomTargetClass</function-class>
    		<function-signature>java.lang.String today()</function-signature>
    		<example>
    			<![CDATA[
    				${customtargetclass:today()}
    			]]>
    		</example>
    	</function>
    	<function>
    		<description>multiple의 활용</description>
    		<name>multiple</name>
    		<function-class>kr.or.ddit.utiles.CustomTargetClass</function-class>
    		<function-signature>java.lang.Integer multiple(java.lang.String, java.lang.Integer)</function-signature>
    		<example>
    			<![CDATA[
    				${customtargetclass:multiple(java.lang.String, java.lang.Integer)}
    			]]>
    		</example>
    	</function>
    
    		}								
    										
    	}
    	
    	BufferedWriter writer = null;
    	
    	try{
    		writer = new BufferedWriter(new FileWriter(new File("D:\\temp\\"+className.toLowerCase()+ ".tld")));
            
    		writer.write(declareStart+declareContent+declareEnd);
            
    	}catch(IOException e){
        
    		e.printStackTrace();
            
    	}finally{
        
    		writer.close();
    	}
    %>
    <!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>
    </head>
    <body>
    사용자 정의 태그가 작성되었습니다.
    </body>
    </html>

     

    댓글

Designed by Tistory.