search
HomeJavajavaTutorialExample of operating FreeMarker templates based on Java's Spring framework

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项目图

Example of operating FreeMarker templates based on Javas Spring framework

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

更多Example of operating FreeMarker templates based on Javas Spring framework相关文章请关注PHP中文网!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What aspects of Java development are platform-dependent?What aspects of Java development are platform-dependent?Apr 26, 2025 am 12:19 AM

Javadevelopmentisnotentirelyplatform-independentduetoseveralfactors.1)JVMvariationsaffectperformanceandbehavioracrossdifferentOS.2)NativelibrariesviaJNIintroduceplatform-specificissues.3)Filepathsandsystempropertiesdifferbetweenplatforms.4)GUIapplica

Are there performance differences when running Java code on different platforms? Why?Are there performance differences when running Java code on different platforms? Why?Apr 26, 2025 am 12:15 AM

Java code will have performance differences when running on different platforms. 1) The implementation and optimization strategies of JVM are different, such as OracleJDK and OpenJDK. 2) The characteristics of the operating system, such as memory management and thread scheduling, will also affect performance. 3) Performance can be improved by selecting the appropriate JVM, adjusting JVM parameters and code optimization.

What are some limitations of Java's platform independence?What are some limitations of Java's platform independence?Apr 26, 2025 am 12:10 AM

Java'splatformindependencehaslimitationsincludingperformanceoverhead,versioncompatibilityissues,challengeswithnativelibraryintegration,platform-specificfeatures,andJVMinstallation/maintenance.Thesefactorscomplicatethe"writeonce,runanywhere"

Explain the difference between platform independence and cross-platform development.Explain the difference between platform independence and cross-platform development.Apr 26, 2025 am 12:08 AM

Platformindependenceallowsprogramstorunonanyplatformwithoutmodification,whilecross-platformdevelopmentrequiressomeplatform-specificadjustments.Platformindependence,exemplifiedbyJava,enablesuniversalexecutionbutmaycompromiseperformance.Cross-platformd

How does Just-In-Time (JIT) compilation affect Java's performance and platform independence?How does Just-In-Time (JIT) compilation affect Java's performance and platform independence?Apr 26, 2025 am 12:02 AM

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

Why is Java a popular choice for developing cross-platform desktop applications?Why is Java a popular choice for developing cross-platform desktop applications?Apr 25, 2025 am 12:23 AM

Javaispopularforcross-platformdesktopapplicationsduetoits"WriteOnce,RunAnywhere"philosophy.1)ItusesbytecodethatrunsonanyJVM-equippedplatform.2)LibrarieslikeSwingandJavaFXhelpcreatenative-lookingUIs.3)Itsextensivestandardlibrarysupportscompr

Discuss situations where writing platform-specific code in Java might be necessary.Discuss situations where writing platform-specific code in Java might be necessary.Apr 25, 2025 am 12:22 AM

Reasons for writing platform-specific code in Java include access to specific operating system features, interacting with specific hardware, and optimizing performance. 1) Use JNA or JNI to access the Windows registry; 2) Interact with Linux-specific hardware drivers through JNI; 3) Use Metal to optimize gaming performance on macOS through JNI. Nevertheless, writing platform-specific code can affect the portability of the code, increase complexity, and potentially pose performance overhead and security risks.

What are the future trends in Java development that relate to platform independence?What are the future trends in Java development that relate to platform independence?Apr 25, 2025 am 12:12 AM

Java will further enhance platform independence through cloud-native applications, multi-platform deployment and cross-language interoperability. 1) Cloud native applications will use GraalVM and Quarkus to increase startup speed. 2) Java will be extended to embedded devices, mobile devices and quantum computers. 3) Through GraalVM, Java will seamlessly integrate with languages ​​such as Python and JavaScript to enhance cross-language interoperability.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.