1. 문자열을 통해 템플릿 개체를 만들고 보간 처리를 수행합니다.
Freemarker.template.template 가져 오기; import java.io.outputStreamwriter; import java.io.stringReader; java.util.hashmap import; java.util.map import; /** * 프리 마커의 가장 간단한 예 * * @Author Leizhimin 11-11-17 10:32 AM */public class test2 {public static void main (String [] args)은 예외를 던졌습니다 {// 템플릿 객체 템플릿 생성 t = new Template (null, new stringReader ( "username : $ {user}; $}; null); // 보간 된지도 맵 맵 맵 = new Hashmap (); map.put ( "사용자", "lavasoft"); map.put ( "url", "http://www.baidu.com/"); map.put ( "이름", "baidu"); // 지정된 출력 스트림 T.process (MAP, New OutputStreamWriter (System.out))에 보간 및 출력을 실행합니다. }} 실행 후 콘솔은 결과를 출력합니다.
사용자 이름 : lavasoft; url : http://www.baidu.com/;name : Exit Code 0으로 완료되었습니다.
2. 파일을 통해 템플릿 개체를 만들고 보간 작업을 수행합니다.
Freemarker.template.configuration 가져 오기; Freemarker.template.template 가져 오기; import java.io.file; import java.io.outputStreamwriter; java.util.hashmap import; java.util.map import; / ** * 프리 마커의 가장 간단한 예 * * @Author Leizhimin 11-11-14 2:44 PM */ Public Class Test {개인 구성 CFG; // 템플릿 구성 객체 public void init ()는 예외 {// 프리 마커 구성 초기화 // 구성 인스턴스 생성 cfg = new configuration (); // 프리 마커 CFG의 템플릿 폴더 위치 설정 (새 파일 ( "g : // testProjects // freemarkerTest // src"); } public void process ()는 예외를 던집니다 {// 데이터 맵을 채우는 맵 맵 맵을 작성하십시오 맵 = new Hashmap (); map.put ( "사용자", "lavasoft"); map.put ( "url", "http://www.baidu.com/"); map.put ( "이름", "baidu"); // 템플릿 객체 템플릿 생성 t = cfg.getTemplate ( "test.ftl"); // 템플릿에서 보간 작업을 수행하고 공식화 된 출력 스트림 T.Process (MAP, New OutputStreamWriter (System.out))에 대한 출력; } public static void main (string [] args)은 예외를 {test hf = new test (); hf.init (); hf.process (); }}
템플릿 파일 test.ftl을 만듭니다
<html> <head> <title> 환영합니다! </title> </head> <h1> 환영 $ {user}! </h1> <p> 최신 제품 : <a href = "$ {url}"> $ {name} </a>! </body> </html> 안녕하세요, 친애하는 사용자 : 사용자 이름 : $ {user}; URL : $ {url}; 이름 : $ {name}
실행 후 콘솔 출력 결과는 다음과 같습니다.
<html> <head> <title> 환영합니다! </title> </head> <hoad> <h1> Lavasoft를 환영합니다! </h1> <p> 우리의 최신 제품 : <a href = "http://www.baidu.com/"> baidu </a>! </body> </html>
안녕하세요, 친애하는 사용자 :
사용자 이름 : Lavasoft; URL : http://www.baidu.com/; 이름 : Baidu 프로세스 Exit 코드 0으로 완료되었습니다
3. 주석 기반 스프링+프리 마커 인스턴스
웹 프로젝트 다이어그램
web.xml 파일
<? xml version = "1.0"encoding = "utf-8"?> <web-app id = "webapp_id"version = "2.4"xmlns = "http://java.sun.com/xml/ns/j2ee"xmlns : xsi = "http://www.w.w3.org/2001/xmlschema-instance. xsi : schemalocation = "http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <servlet> <!-configure dispatcherservlet-> <servlet-name> springmvc </letmvc </let-name> <Servlet-class> org.springframework.web.servlet.dispatcherServlet </servlet-class> <!-기본 사용법을 지정하지 않고 스프링 MVC 구성 파일 위치를 지정합니다-> <init-param> <param-name> ContextConfigLocation </param-name> <param-value> /web-inf/springmvc-servlet.xml </param-value> <!-기본 :/web-inf/<servlet-name> -servlet.xml classpath 메소드 : <param- value> classpath :/spring-xml/*. xml </param-value >-> </init-param> <! </load-on-startup> </servlet> <!-servlet-name을 맵핑하고 servlet-name에 맵핑하는 서플릿을 구성합니다-> <servlet-mapping> <servlet-name> springmvc </servlet-name> <url-pattern>/</url-pattern> <! <welcome-file> index.jsp </welcome-file> </welcome-file-list> </web-app>
SpringMvc-servlet.xml 파일
<? xml version = "1.0"encoding = "utf-8"?> <beans xmlns = "http://www.springframework.org/schema/beans"xmlns : aop = "http://www.springframework.org/aop" xmlns : xsi = "http://www.w3.org/2001/xmlschema-instance"xmlns : p = "http://www.springframework.org/schema/p"xmlns : mvc = "http://www.spramframwork.org/schema/gramework.org/schema/g xmlns : context = "http://www.springframework.org/schema/context"xsi : schemalocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/schema/sprideans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/context http://www.spramework.org/schema/context/spring-cont.x xt.xt.xsd 지원-> <mvc : 주석 구동 /> <!-자동 스캐닝 패키지-> <context : component-scan base-package = "com.spring.freemarker" /> <!-<context : annotation-config /> 구성 패키지 구성이 구성이 자동 스캔이 될 수 있습니다. -> <!-프리 마커의 템플릿 경로를 구성-> <bean> <속성 이름 = "templateloaderPath"value = "web-inf /ftl /" /> <property name = "defaultencoding"value = "utf-8" /> < /bean> <! <!-freemarker view parser-> bean> <valuix "= ftl" / / / / /<valuix ". value = "text/html; charset = utf-8"/> <!-이 변수 값은 pagecontext.request입니다.
FreemarkerController 클래스
패키지 com.spring.freemarker; java.util.arraylist 가져 오기; Java.util.list 가져 오기; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; org.springframework.stereotyp.controller import; org.springframework.web.bind.annotation.requestmapping; org.springframework.web.servlet.modelandview import; import com.spring.vo.user; @controller @requestmapping ( "/home") 공개 클래스 FreemarkErconTroller {@requestmapping ( "/index") public modelandview add (httpservletrequest request, httpservletrepsonge 응답) {user user = 새 사용자 (); user.setusername ( "zhangsan"); user.setpassword ( "1234"); List <user> user = new ArrayList <user> (); user.add (사용자); 새로운 ModelAndView ( "색인", "사용자", 사용자)을 반환합니다. }}사용자 클래스
패키지 com.spring.vo; 공개 클래스 사용자 {개인 문자열 사용자 이름; 개인 문자열 비밀번호; public String getUserName () {return username; } public void setusername (String username) {this.username = username; } public String getPassword () {return password; } public void setpassword (문자열 비밀번호) {this.password = password; }}
index.ftl 파일
<! docType html public "-// w3c // dtd html 4.01 Transitional // en" "http://www.w3.org/tr/html4/loose.dtd"> <html> <head> <meta http-equiv = "content-type" <title> 제목을 여기에 삽입 </title> </head> <body> <##us user> username : $ {user.username} <br/> 비밀번호 : $ {user.password} </#list> </body> </html> Tomcat에 배포 및 실행 : http : // localhost : 8080/springmvc/home/index
결과 표시 :
사용자 이름 : Zhangsan 비밀번호 : 1234