본문 바로가기
Developer/Java, Spring

[WEB] JSTL 메서드, java 함수 접근 하기

by ParkjuGod 2017. 1. 11.

JSTL 메서드, java 함수 접근 하기




JSP 에서 이미지를 불러올 때 파일명을 바꿀 일이 생겼다.

예를 들면 example.jpg 를 example_tmb.jpg 로 바꿔야 했다.


디비에서 꺼내 올때 바꿔도 되지만 좀더 쉬운 방법을 찾아보던 중 jstl에서 메서드를 호출 할 수 있다는걸 알게 되었고 적용을 해보기로 한다....



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?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.0">
 
     <description>elFunction</description>
     <tlib-version>1.2</tlib-version>
     <short-name>ELfunctions</short-name>
     <uri>/ELFunctions</uri>
     <function>
         <description>이미지URL -> 썸네일 URL 변경</description>
         <name>makeThumbnailUrl</name>
         <function-class>com.test.util.JstlUtil</function-class>
         <function-signature>
              String makeThumbnailUrl(java.lang.String)
         </function-signature>
    </function>
</taglib>
cs

WEB-INF/tld/elFunction.tld


위 파일은 무조건 WEB-INF 안에 있어야 한다. 

처음 소스를 불러올때 같이 불러오기 때문에 

자바 메서드를 인식 할수 있게 되는것이다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class JstlUtil {
    
    /**
     * @param path
     * @return 이미지URL -> 썸네일 URL 변경
     */
    public static String makeThumbnailUrl(String path){
        String pathExt = path.substring(path.lastIndexOf(".")+1);
        String postfix = "_tmb";
        if("jpg|png|jpeg|gif".indexOf(pathExt) < 0){
            return path;
        } else {
            return path.substring(0, path.lastIndexOf(".")) + postfix + "." + pathExt;
        }
    }
    
}
cs

com/test/util/JstlUtil.java


위 처럼 자바로 UTIL 을 만들자


1
2
3
4
<%@ taglib prefix="te" uri="/WEB-INF/tlds/elFunctions.tld" %>
 
<!-- html 코드 -->
${te.makeThumbnailUrl( param ) }
cs


이런식으로 사용 하면 끝이다.


정말 쉽지 않은가?

반응형

'Developer > Java, Spring' 카테고리의 다른 글

[JAVA] GSON 사용법  (0) 2023.06.21
[java] SimpleDateFormat YYYY 쓰지마라  (0) 2019.01.02