Java의 Spring 프레임워크를 기반으로 FreeMarker 템플릿을 운영하는 예
1、通过String来创建模版对象,并执行插值处理
import freemarker.template.Template; import java.io.OutputStreamWriter; import java.io.StringReader; import java.util.HashMap; import java.util.Map; /** * Freemarker最简单的例子 * * @author leizhimin 11-11-17 上午10:32 */ public class Test2 { public static void main(String[] args) throws Exception{ //创建一个模版对象 Template t = new Template(null, new StringReader("用户名:${user};URL: ${url};姓名: ${name}"), null); //创建插值的Map Map map = new HashMap(); map.put("user", "lavasoft"); map.put("url", "http://www.baidu.com/"); map.put("name", "百度"); //执行插值,并输出到指定的输出流中 t.process(map, new OutputStreamWriter(System.out)); } }
执行后,控制台输出结果:
用户名:lavasoft; URL: http://www.baidu.com/; 姓名: 百度 Process finished with exit code 0
2、通过文件来创建模版对象,并执行插值操作
import freemarker.template.Configuration; import freemarker.template.Template; import java.io.File; import java.io.OutputStreamWriter; import java.util.HashMap; import java.util.Map; /** * Freemarker最简单的例子 * * @author leizhimin 11-11-14 下午2:44 */ public class Test { private Configuration cfg; //模版配置对象 public void init() throws Exception { //初始化FreeMarker配置 //创建一个Configuration实例 cfg = new Configuration(); //设置FreeMarker的模版文件夹位置 cfg.setDirectoryForTemplateLoading(new File("G:\\testprojects\\freemarkertest\\src")); } public void process() throws Exception { //构造填充数据的Map Map map = new HashMap(); map.put("user", "lavasoft"); map.put("url", "http://www.baidu.com/"); map.put("name", "百度"); //创建模版对象 Template t = cfg.getTemplate("test.ftl"); //在模版上执行插值操作,并输出到制定的输出流中 t.process(map, new OutputStreamWriter(System.out)); } public static void main(String[] args) throws Exception { Test hf = new Test(); hf.init(); hf.process(); } }
创建模版文件test.ftl
<html> <head> <title>Welcome!</title> </head> <body> <h1 id="Welcome-nbsp-user">Welcome ${user}!</h1> <p>Our latest product: <a href="${url}">${name}</a>! </body> </html>
尊敬的用户你好: 用户名:${user}; URL: ${url}; 姓名: ${name}
执行后,控制台输出结果如下:
<html> <head> <title>Welcome!</title> </head> <body> <h1 id="Welcome-nbsp-lavasoft">Welcome lavasoft!</h1> <p>Our latest product: <a href="http://www.baidu.com/">百度</a>! </body> </html>
尊敬的用户你好:
用户名:lavasoft; URL: http://www.baidu.com/; 姓名: 百度 Process finished with exit code 0
3.基于注解的Spring+freemarker实例
web项目图
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.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> <!-- 配置DispatcherServlet --> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 指定spring 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>1</load-on-startup> </servlet> <!-- 配置映射 servlet-name和DispatcherServlet的servlet一致 --> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern><!-- 拦截以/所有请求 --> </servlet-mapping> <welcome-file-list> <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/schema/aop" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.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.springframework.org/schema/context/spring-context.xsd"> <!-- 默认注解映射支持 --> <mvc:annotation-driven/> <!-- 自动扫描包 --> <context:component-scan base-package="com.spring.freemarker" /> <!--<context:annotation-config /> 配置自动扫描包配置此配置可省略--> <!--<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" 配置自动扫描包配置此配置可省略/>--> <!-- 配置freeMarker的模板路径 --> <bean class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer"> <property name="templateLoaderPath" value="WEB-INF/ftl/" /> <property name="defaultEncoding" value="UTF-8" /> </bean> <!-- freemarker视图解析器 --> <bean class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver"> <property name="suffix" value=".ftl" /> <property name="contentType" value="text/html;charset=UTF-8" /> <!-- 此变量值为pageContext.request, 页面使用方法:rc.contextPath --> <property name="requestContextAttribute" value="rc" /> </bean> </beans>
FreeMarkerController类
package com.spring.freemarker; import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import com.spring.vo.User; @Controller @RequestMapping("/home") public class FreeMarkerController { @RequestMapping("/index") public ModelAndView Add(HttpServletRequest request, HttpServletResponse response) { User user = new User(); user.setUsername("zhangsan"); user.setPassword("1234"); List<User> users = new ArrayList<User>(); users.add(user); return new ModelAndView("index", "users", users); } }
User类
package com.spring.vo; public class User { private String username; private String password; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { 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" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <#list users as user> username : ${user.username}<br/> password : ${user.password} </#list> </body> </html>
部署到tomcat,运行:http://localhost:8080/springmvc/home/index
显示结果:
username : zhangsan password : 1234
更多Java의 Spring 프레임워크를 기반으로 FreeMarker 템플릿을 운영하는 예相关文章请关注PHP中文网!

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











이 기사는 2025 년에 상위 4 개의 JavaScript 프레임 워크 (React, Angular, Vue, Svelte)를 분석하여 성능, 확장 성 및 향후 전망을 비교합니다. 강력한 공동체와 생태계로 인해 모두 지배적이지만 상대적으로 대중적으로

Java의 클래스 로딩에는 부트 스트랩, 확장 및 응용 프로그램 클래스 로더가있는 계층 적 시스템을 사용하여 클래스로드, 링크 및 초기화 클래스가 포함됩니다. 학부모 위임 모델은 핵심 클래스가 먼저로드되어 사용자 정의 클래스 LOA에 영향을 미치도록합니다.

이 기사는 카페인 및 구아바 캐시를 사용하여 자바에서 다단계 캐싱을 구현하여 응용 프로그램 성능을 향상시키는 것에 대해 설명합니다. 구성 및 퇴거 정책 관리 Best Pra와 함께 설정, 통합 및 성능 이점을 다룹니다.

이 기사는 원격 코드 실행을 허용하는 중요한 결함 인 Snakeyaml의 CVE-2022-1471 취약점을 다룹니다. Snakeyaml 1.33 이상으로 Spring Boot 응용 프로그램을 업그레이드하는 방법에 대해 자세히 설명합니다.

Node.js 20은 V8 엔진 개선, 특히 더 빠른 쓰레기 수집 및 I/O를 통해 성능을 크게 향상시킵니다. 새로운 기능에는 더 나은 webAssembly 지원 및 정제 디버깅 도구, 개발자 생산성 및 응용 속도 향상이 포함됩니다.

대규모 분석 데이터 세트를위한 오픈 테이블 형식 인 Iceberg는 데이터 호수 성능 및 확장 성을 향상시킵니다. 내부 메타 데이터 관리를 통한 Parquet/Orc의 한계를 해결하여 효율적인 스키마 진화, 시간 여행, 동시 W를 가능하게합니다.

이 기사는 Lambda 표현식, 스트림 API, 메소드 참조 및 선택 사항을 사용하여 기능 프로그래밍을 Java에 통합합니다. 간결함과 불변성을 통한 개선 된 코드 가독성 및 유지 관리 가능성과 같은 이점을 강조합니다.

이 기사에서는 Java 프로젝트 관리, 구축 자동화 및 종속성 해상도에 Maven 및 Gradle을 사용하여 접근 방식과 최적화 전략을 비교합니다.
