사용자 정의 태그 (1)

💻 Programming/JSP

[JSP] Custom Tags ( 커스텀, 사용자 정의 태그 )

커스텀 태그를 갖고 있는 JSP페이지가 서블릿으로 변환될 때, 그 태그는 tag handler라고 불리는 객체의 operation으로 변환됩니다. 그리고나서 JSP페이지의 서블릿이 실행될 때 웹컨테이너가 그 opreation을 호출하게 되는 거죠.

JSP tag extensions 는 JSP에 직접 추가할 수 있는 새로운 태그를 만들 수 있도록 해줍니다. JSP 2.0 specification에는 이런 커스텀 태그를 쓰기위한 Simple Tag Handlers 를 제공합니다.

customer tag를 쓰려면 단순히 SimpleTagSupport 를 상속하고  doTag()메소드를 오버라이드 하면 됩니다.  

 

Create "Hello" Tag ( 사용자 정의 태그 생성하기 )

아래처럼  <ex:Hello> 를 쓰고싶다고 가정해봅시다. body 태그도 없이 말입니다. 

<ex:Hello />

custom JSP tag를 만들려면 태그 핸들러 Java class 부터 만들어야 합니다. 

아래처럼 자바 코딩을 해봅시다. 

package com.tutorialspoint; import javax.servlet.jsp.tagext.*; import javax.servlet.jsp.*; import java.io.*; public class HelloTag extends SimpleTagSupport { public void doTag() throws JspException, IOException { JspWriter out = getJspContext().getOut(); out.println("Hello Custom Tag!"); } }

위 코드는 doTag() 메소드에서 getJspContext() method를 이용해서 현재 JspContext object를 얻어오고 "Hello Custom Tag!"메시지를  JspWriter 객체로 보내는 기능을 넣은 것입니다.

 

이제 이 소스파일을 컴파일해서 class파일로 만들고 이 클래스 파일을 환경변수 CLASSPATH에 지정되어있는 곳에 복사해서 넣어주세요. 마지막으로 아래와 같은 태그라이브러리 파일을 생성하면 됩니다. 위치는 아래와 같습니다.

 <Tomcat-Installation-Directory>webapps\ROOT\WEB-INF\custom.tld

<taglib> <tlib-version>1.0</tlib-version> <jsp-version>2.0</jsp-version> <short-name>Example TLD</short-name> <tag> <name>Hello</name> <tag-class>com.tutorialspoint.HelloTag</tag-class> <body-content>empty</body-content> </tag> </taglib>

이제 JSP파일에서 이 Hello 태그를 사용해 봅시다.  

<%@ taglib prefix="ex" uri="WEB-INF/custom.tld"%> <html> <head> <title>A sample custom tag</title> </head> <body> <ex:Hello/> </body> </html>

이제 만들어진 JSP파일을 웹브라우저에서 요청해 보세요. 아래와 같은 결과가 나올 것입니다. 

Hello Custom Tag!


Accessing the Tag Body ( 태그 바디에 접근하기 )

커스텀 태그도 일반 HTML태그처럼 시작태그와 종료태그 사이에 바디부분을 추가할 수 있습니다.

<ex:Hello> This is message body </ex:Hello>

위에서 작성했던 자바소스를 아래처럼 변경합니다. 

package com.tutorialspoint; import javax.servlet.jsp.tagext.*; import javax.servlet.jsp.*; import java.io.*; public class HelloTag extends SimpleTagSupport { StringWriter sw = new StringWriter(); public void doTag() throws JspException, IOException { getJspBody().invoke(sw); getJspContext().getOut().println(sw.toString()); } }

여기서는 StringWriter로 읽어들인 후에 읽어들인 값을 JspWriter에서 처리하는 방식입니다.

TLD 파일도 아래처럼 변경되어야 합니다.

<taglib> <tlib-version>1.0</tlib-version> <jsp-version>2.0</jsp-version> <short-name>Example TLD with Body</short-name> <tag> <name>Hello</name> <tag-class>com.tutorialspoint.HelloTag</tag-class> <body-content>scriptless</body-content> </tag> </taglib>

JSP파일은 아래처럼 변경합니다.

<%@ taglib prefix="ex" uri="WEB-INF/custom.tld"%> <html> <head> <title>A sample custom tag</title> </head> <body> <ex:Hello> This is message body </ex:Hello> </body> </html>

결과는 아래처럼 나와야 합니다.

This is message body


Custom Tag Attributes ( 커스텀 태그의 속성 )

 custom tags는 속성과 함께 사용될 수도 있습니다.  속성값을 받으려면 custom tag class는 setter methods를 구현해야 합니다. JavaBean setter methods와 동일하게 말이죠. 

package com.tutorialspoint; import javax.servlet.jsp.tagext.*; import javax.servlet.jsp.*; import java.io.*; public class HelloTag extends SimpleTagSupport { private String message; public void setMessage(String msg) { this.message = msg; } StringWriter sw = new StringWriter(); public void doTag() throws JspException, IOException { if (message != null) { /* Use message from attribute */ JspWriter out = getJspContext().getOut(); out.println( message ); } else { /* use message from the body */ getJspBody().invoke(sw); getJspContext().getOut().println(sw.toString()); } } }

속성명은 "message"이고 세터메소드는 당연히 setMessage()가 되겠죠. 이제 이 속성을 TLD file에 추가합니다. <attribute> 요소를 이용해서 말이죠.

<taglib> <tlib-version>1.0</tlib-version> <jsp-version>2.0</jsp-version> <short-name>Example TLD with Body</short-name> <tag> <name>Hello</name> <tag-class>com.tutorialspoint.HelloTag</tag-class> <body-content>scriptless</body-content> <attribute> <name>message</name> </attribute> </tag> </taglib>

JSP파일에 메시지 속성을 이용한 태그를 추가하세요. 

<%@ taglib prefix="ex" uri="WEB-INF/custom.tld"%> <html> <head> <title>A sample custom tag</title> </head> <body> <ex:Hello message="This is custom tag" /> </body> </html>

결과는 아래처럼 나올 것입니다.

This is custom tag

 

 

속성에는 아래와 같은 프로퍼티들이 들어갈 수 있습니다.

PropertyPurpose
nameThe name element defines the name of an attribute. Each attribute name must be unique for a particular tag.
requiredThis specifies if this attribute is required or optional. It would be false for optional.
rtexprvalueDeclares if a runtime expression value for a tag attribute is valid
typeDefines the Java class-type of this attribute. By default it is assumed as String
descriptionInformational description can be provided.
fragmentDeclares if this attribute value should be treated as a JspFragment.

 

속성 관련 프로퍼티를 설정하는 방법은 아래와 같습니다.

.....
    <attribute>
      <name>attribute_name</name>
      <required>false</required>
      <type>java.util.Date</type>
      <fragment>false</fragment>
    </attribute>
.....

두 개 이상의 속성을 사용한다면 TLD파일에 아래처럼 추가하면 됩니다.

..... <attribute> <name>attribute_name1</name> <required>false</required> <type>java.util.Boolean</type> <fragment>false</fragment> </attribute> <attribute> <name>attribute_name2</name> <required>true</required> <type>java.util.Date</type> </attribute>

.....





Reference : http://www.tutorialspoint.com/jsp/jsp_custom_tags.htm


'💻 Programming > JSP' 카테고리의 다른 글

[JSP] Implicit Objects ( 묵시적 객체들 )  (0) 2019.02.15
[JSP] Actions ( 액션 )  (0) 2019.02.15
[JSP] Directives ( 디렉티브 )  (0) 2019.02.15
[JSP] JSP 생명 주기 ( life cycle )  (0) 2019.02.15
[JSP] 조건문, 반복문  (0) 2019.02.15