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>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>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中文网!

JavadevelovermentIrelyPlatForm-DeTueTososeVeralFactors.1)JVMVariationsAffectPerformanceNandBehaviorAcroSsdifferentos.2)Nativelibrariesviajnijniiniininiinniinindrododerplatefform.3)

Java代码在不同平台上运行时会有性能差异。1)JVM的实现和优化策略不同,如OracleJDK和OpenJDK。2)操作系统的特性,如内存管理和线程调度,也会影响性能。3)可以通过选择合适的JVM、调整JVM参数和代码优化来提升性能。

Java'splatFormentenceHaslimitations不包括PerformanceOverhead,versionCompatibilityIsissues,挑战WithnativelibraryIntegration,Platform-SpecificFeatures,andjvminstallation/jvminstallation/jvmintenance/jeartenance.therefactorscomplicatorscomplicatethe“ writeOnce”

PlatformIndependendecealLowsProgramStormonanyPlograwsStormanyPlatFormWithOutModification,而LileCross-PlatFormDevelopmentRequiredquiresMomePlatform-specificAdjustments.platFormIndependence,EneblesuniveByjava,EnablesuniversUniversAleversalexecutionbutmayCotutionButMayComproMisePerformance.cross.cross.cross-platformd

JITcompilationinJavaenhancesperformancewhilemaintainingplatformindependence.1)Itdynamicallytranslatesbytecodeintonativemachinecodeatruntime,optimizingfrequentlyusedcode.2)TheJVMremainsplatform-independent,allowingthesameJavaapplicationtorunondifferen

javaispopularforcross-platformdesktopapplicationsduetoits“ writeonce,runanywhere”哲学。1)itusesbytbytybytecebytecodethatrunsonanyjvm-platform.2)librarieslikeslikeslikeswingingandjavafxhelpcreatenative-lookingenative-lookinguisis.3)

在Java中编写平台特定代码的原因包括访问特定操作系统功能、与特定硬件交互和优化性能。1)使用JNA或JNI访问Windows注册表;2)通过JNI与Linux特定硬件驱动程序交互;3)通过JNI使用Metal优化macOS上的游戏性能。尽管如此,编写平台特定代码会影响代码的可移植性、增加复杂性、可能带来性能开销和安全风险。

Java将通过云原生应用、多平台部署和跨语言互操作进一步提升平台独立性。1)云原生应用将使用GraalVM和Quarkus提升启动速度。2)Java将扩展到嵌入式设备、移动设备和量子计算机。3)通过GraalVM,Java将与Python、JavaScript等语言无缝集成,增强跨语言互操作性。


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

安全考试浏览器
Safe Exam Browser是一个安全的浏览器环境,用于安全地进行在线考试。该软件将任何计算机变成一个安全的工作站。它控制对任何实用工具的访问,并防止学生使用未经授权的资源。

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

DVWA
Damn Vulnerable Web App (DVWA) 是一个PHP/MySQL的Web应用程序,非常容易受到攻击。它的主要目标是成为安全专业人员在合法环境中测试自己的技能和工具的辅助工具,帮助Web开发人员更好地理解保护Web应用程序的过程,并帮助教师/学生在课堂环境中教授/学习Web应用程序安全。DVWA的目标是通过简单直接的界面练习一些最常见的Web漏洞,难度各不相同。请注意,该软件中

EditPlus 中文破解版
体积小,语法高亮,不支持代码提示功能

VSCode Windows 64位 下载
微软推出的免费、功能强大的一款IDE编辑器