본문 바로가기
Template

Servlet + Freemarker (프리마커)

by 수앙 2011. 9. 11.

사이트 http://freemarker.sourceforge.net/

매뉴얼 http://freemarker.sourceforge.net/docs/index.html


방법1. web.xml 파일에 등록하여 처리

<servlet>

<servlet-name>freemarker</servlet-name>

<servlet-class>freemarker.ext.servlet.FreemarkerServlet</servlet-class>

<!-- FreemarkerServlet settings: -->

<init-param>

<param-name>TemplatePath</param-name>

<param-value>/</param-value>

</init-param>

<init-param>

<param-name>NoCache</param-name>

<param-value>true</param-value>

</init-param>

<init-param>

<param-name>ContentType</param-name>

<param-value>text/html; charset=UTF-8</param-value> <!-- Forces UTF-8 output encoding! -->

</init-param>

<!-- FreeMarker settings: -->

<init-param>

<param-name>template_update_delay</param-name>

<param-value>0</param-value> <!-- 0 is for development only! Use higher value otherwise. -->

</init-param>

<init-param>

<param-name>default_encoding</param-name>

<param-value>UTF-8</param-value> <!-- The encoding of the template files. -->

</init-param>

<init-param>

<param-name>output_encoding</param-name>

<param-value>UTF-8</param-value> <!-- The encoding of the template files. -->

</init-param>

<init-param>

<param-name>number_format</param-name>

<param-value>0.##########</param-value>

</init-param>

<load-on-startup>1</load-on-startup>

</servlet>


<servlet-mapping>

<servlet-name>freemarker</servlet-name>

<url-pattern>*.ftl</url-pattern>

</servlet-mapping>


방법2. Servlet 파일에서 처리 (Freemarker 설정 값도 지정해줘야 함)    

public void process(HttpServletRequest req, HttpServletResponse resp) throws IOException {

// webapp

TemplateLoader loader = new WebappTemplateLoader(getServletContext(), "");


// class

loader = new ClassTemplateLoader(getClass(), "");


// directory

loader = new FileTemplateLoader(new File("D:/dev/workspace/jsp/WebContent"));


// string

StringTemplateLoader stringLoader = new StringTemplateLoader();

stringLoader.putTemplate("index.ftl", "${greeting}");

loader = stringLoader;


Configuration cfg = new Configuration();

cfg.setTemplateLoader(loader);

Template template = cfg.getTemplate("index.ftl");

PrintWriter out = resp.getWriter();

HashMap<String, String> map = new HashMap<String, String>();

map.put("greeting", "Hello World");

try {

template.process(map, out);

} catch (TemplateException e) {

e.printStackTrace();

}

out.flush();

}


끝.

'Template' 카테고리의 다른 글

eclipse 3.7.1 Indigo velocity editor plugin 설치  (0) 2011.12.17
Velocity 설정 및 사용법  (0) 2011.09.14
Freemarker 파싱  (0) 2011.07.12

댓글