본문 바로가기
JAVA

[JSP] Custom Tag <커스텀태그>

by HANdeveloper 2022. 8. 21.
custom tag

- 스크립트 요소가 많아질수록 JSP코드가 복잡해지는데 이런 문제점 해결하기 위해서

  JSP가 기본적으로 제공하는 액션태그, JSTL이 제공하는 태그, 스크립트 코드 그리고  EL을 통해 원하는 기능을 구현함

- 하지만 이 코드들로 아쉬울 때가 있어 사용자 지정태그를 만들어 사용함

- 원하는 목적에 맞게 작성한 태그를 '커스텀태그', '사용자 지정태그'라고 부름

 

 

▶ 커스텀 태그 장점

  • 재사용성 
  • 역할분담
  • 유지보수성
  • 가독성

▶ 클래스 기반 구성요소

태그 핸들러 클래스 - 커스텀 태그를 사용할 때 호출되는 자바 클래스 파일
- 커스텀 태그가 수행해야 하는 실행문을 구현하고 있는 자바객체
태그 라이브러리 디스크립터(TLD) - 실제 로직이 구현된 클래스파일을 어떤 jsp 태그 이름으로
  사용할지를 설정하는 XML파일 (확장자 : .tld)
TLD 파일등록 - TLD파일에는 자바클래스와 JSP태그를 매핑한 정보가 있음
- WEB-INF폴더에 넣으면 JSP 컨테이너가 자동으로 인식함
taglib 지시자 - jsp페이지에서 커스텀태그를 사용하려면 우선 어떤 커스텀     
  태그를 사용할지를 taglib 지시자를 사용하여 선언
- uri와 perfix 값을 속성으로 가짐
- taglib지시자는 커스텀태그가 정의된 TLD와 JSP 파일을 연결

커스텀 태그 핸들러

- tagSupport를 상속받아 doStartTag(), doEndTag() 메소드를 override 함

- 이 때 중요한 점은 태그에 사용될 속성의 setter 메소드를 만들어야함

- 여기서는 setName()이라는 하나의 setter 메소드를 정의

 

< HelloAttributeTag.java >

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
public class HelloAttributeTag extends TagSupport {
 
    private String name;
 
    public HelloAttributeTag() {
        System.out.println("1.HelloAttributeTag 기본생성자");
    }
 
    public void setName(String name) {
        System.out.println("2.HelloAttributeTag.setName(" + name+ ")");
        this.name = name;
    }
 
    @Override
    public int doStartTag() throws JspException {
        System.out.println("3.HelloAttributeTag.doStartTag()");
        String msg = "";
        if (name.equals("사과")) {
            msg = "예쁜 " + name + " 님 안녕하세요:)<br>";
        } else {
            msg = name + " 님 안녕하세요:)<br>";
        }
        try {
            pageContext.getOut().println(msg);
        } catch (Exception e) {
            e.printStackTrace();
        }
 
        return super.doStartTag();
    }
 
    @Override
    public int doEndTag() throws JspException {
        return super.doEndTag();
    }
}
 
cs

 

▶ TLD  생성

- WEB-INF 하위에 tld 파일을 정의

- attribute에 속성이 필수 속성임을 표시

- body-content의 empty는 태그가 body를 가지고 있지 않다는 것을 의미

 

< helloAttributeTag.tld >

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<?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 web-jsptaglibrary_2_0.xsd" version="2.4">
 
    <description>HelloAttributeTag</description>
    <tlib-version>2.0</tlib-version>
    <short-name>mytag</short-name>
    <uri>http:/yeji-power.tistory.com/jsp/mytag</uri>
    <info>
        A sample tag library
    </info>
    
        <name>helloAttr</name>
        <tagclass>com.tistory.yeji-power.tag.HelloAttributeTag</tagclass>
        <bodycontent>empty</bodycontent>
        <attribute>
            <name>name</name>
            <required>true</required>
            <rtexprvalue>true</rtexprvalue>
            <type>java.lang.String</type>
        </attribute>
    </tag>
    
</taglib>
cs

web.xml 설정

- jsp-config와 taglib 요소를 이용해 jsp커스텀태그를 웹어플리케이션에 포함시킴

- taglib-uri 값은 tld파일에 정의된 것과 동일해야함

- 모든 설정이 완료되었고, 이제 JSP 페이지에서 커스텀 태그 사용가능

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
  <display-name>JSPCustomTags</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
 
  <jsp-config>
  <taglib>
    <taglib-uri>http:/yeji-power.tistory.com/jsp/mytag</taglib-uri>
    <taglib-location>/WEB-INF/helloAttributeTag.tld</taglib-location>
  </taglib>
  </jsp-config>
</web-app>
 
cs

 태그 파일을 이용한 커스텀 태그 구현

- 커스텀 태그를 사용하기 전에 태그 사용한다 선언

<tag lib> 태그 사용하겠다는 태그 라이브러리로 명시 

prefix : "태그 파일 이름" / uri : "JSP페이지에서 TLD파일을 연결할 때 사용할 이름을 지정"

                                     

 

'JAVA' 카테고리의 다른 글

[Spring] DispatcherServlet 개념  (0) 2022.08.29
[Spring] @Annotation 어노테이션이 무엇인가?  (0) 2022.08.26
[JSP] Expression Language (EL)  (0) 2022.08.17
[OOP] 상속화 (Inheritance)  (0) 2022.08.17
[JSP] 기본 객체와 영역  (0) 2022.08.12

댓글