공적's life

custom Tag 만들기 - TagSupport 이용하여 js 꼬리표 붙이기 본문

Programing

custom Tag 만들기 - TagSupport 이용하여 js 꼬리표 붙이기

melpis 2015. 4. 26. 08:12

js꼬리표란? 

브라우저는 js를 호출할때 캐쉬를 합니다. URL 기준으로 


예를 들어서 /test.js를 호출하면 다음에 같은 URL이 호출되면 서버에서 가져오는것이 아니라 로컬에서 가져오게 됩니다.


그럼 조금더 속도가 빨라지겠네요?


이런 장점도 있는 반면에 단점도 있습니다. 위 js가 내용이 바뀐다면 ?? 바뀐 내용이 아닌 기존 js가 로컬에서 호출 되기 때문에


문제가 생깁니다. 사용자 마다 다르게 동작하는 단점이 생기게 됩니다.


이것을 회피 하기 위해서 test.js?123222 이런식으로 임의이 값을 써주게 됩니다.


이렇게 하면 브라우저는 URL기반으로 캐쉬하기 때문에 캐쉬를 피할수 있습니다.


하지만 수많은 js에 저렇게 많은 임의값을 붙이기 위해서는 노가다가 필요하겠죠? 


그래서 생각해낸것이 바로 custom Tag 입니다.


custom Tag만 붙이게 되면 알아서 해주면 안되나 이런생각이 들어서 만들어봤습니다.


만드는 방법은 간단합니다. avax.servlet.jsp.tagext.TagSupport란 클래스를 상속 받아서 구현하기만 하면 됩니다.


1. 클래스

public class ScriptTailTag extends TagSupport {


private static final long serialVersionUID = 1L;

protected String key = null;


public String getKey() {

return this.key;

}


public void setKey(String key) {

this.key = key;

}


@Override

public int doStartTag() throws JspException {

//서버에 절대 경로를 가져옴

String realPath = this.pageContext.getServletContext().getRealPath("");

String fileKey = this.key;

File file = new File(realPath, fileKey);


long lastModified = 0;

//파일이 존재하면 마지막 수정일자를 확인

if (file.exists()) {

lastModified = file.lastModified();

}

//마지막 수정일자를 뒤에 붙여줌

if (lastModified != 0) {

this.key += "?" + lastModified;

}

JspWriter writer = this.pageContext.getOut();

try {

writer.print(this.key);

} catch (IOException e) {

log.error("TagError", e);

}


return SKIP_BODY;

}


}

2. tag 설정 xml

<?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">

    <tlib-version>1.0</tlib-version>

    <uri>script</uri>

 

    <tag>

<name>cache</name>

<tagclass>com.test.ScriptTailTag</tagclass>

<bodycontent>empty</bodycontent>

<info></info>

<attribute>

<name>key</name>

<required>true</required>

</attribute>  

</tag>

</taglib>



3. jsp 설정 

<%@ taglib uri="/WEB-INF/tld/tag.tld"  prefix="script"%>


<script type="text/javascript" src='<script:cache key="/test.js"/>'></script>


이렇게 써주시면 실제 html 변환시 자동으로 뒤에 js꼬리표가 붙게됩니다.


위 코드에서 보시면 알시겠지만 단점도 있습니다.


상대 경로에 대한 처리가 되어 있지 않아서 js경로를 넣을때 절대 경로로 넣어야 한다는것과


script 혹은 css에 사용할때 저 태그를 써야하는것


이 두가지 단점이 있습니다.