这里将展示如何使用Freemarker来进行简单算术运算,逻辑运算,比较运算。
控制器(CaclArithmeticController.java)
package com.test.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; /** * Freemarker的算术运算 * @author Administrator * */ @Controller @RequestMapping("/caclArithmeticController") public class CaclArithmeticController { @RequestMapping("/calculate") public String calculate(ModelMap map){ map.put("x", 34); map.put("y", 12); map.put("z", -12.5); map.put("w", 11.4); map.put("T", true); map.put("F", false); return "/calcArithmetic.ftl"; } }
模板文件(calcArithmetic.ftl)
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>算术运算(+-*/%)</title> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="this is my page"> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> </head> <body> <h3>算术运算</h3> (1)加法: ${x} + ${y} = ${x + y} <br/> (2)减法: ${x} - ${y} = ${x - y} <br/> (3)乘法: ${x} * ${y} = ${x * y} <br/> (4)除法: ${x} / ${y} = ${x / y} <br/> (5)取模: ${x} % ${y} = ${x % y} <br/> (6)获取除数的整数部分: ${x/y} => ${(x/y)?int} <br/><br/> <h3>比较操作(x=${x} y=${y})</h3> (1)= 或 ==,测试两个值是否相等: <#if x = y> <#-- x == y 等价 x = y --> x == y <#else> x != y </#if> <br/> (2)!= 测试不相等: <#if x != y> x != y <#else> x == y </#if> <br/> (3)>: <#if x gt y> (x > y) = YES <#else> (x > y) = NO </#if> <br/> (4)>=: <#if x gte y> (x >= y) = YES <#else> (x >= y) = NO </#if> <br/> (5)<: <#if x lt y> (x < y) = YES <#else> (x < y) = NO </#if> <br/> (6)<=: <#if x lte y> (x <= y) = YES <#else> (x <= y) = NO </#if> <br/> <h3>逻辑运算( T = <#if T> true <#else> false </#if> F = <#if F> true <#else> false </#if>) </h3> (1)逻辑或 || : ${T ? string("true", "false")} || ${F ? string("true", "false")} = ${ (T || F) ? string("yes", "no")} <br/> (2)逻辑与 && : ${T ? string("true", "false")} && ${F ? string("true", "false")} = ${ (T && F) ? string("yes", "no")} <br/> (3)逻辑非 ! : !${T ? string("true", "false")} = ${ (!T) ? string("yes", "no")} <br/> </body> </html>
输出结果:
(1)加法: 34 + 12 = 46
(2)减法: 34 - 12 = 22
(3)乘法: 34 * 12 = 408
(4)除法: 34 / 12 = 2.833
(5)取模: 34 % 12 = 10
(6)获取除数的整数部分: 2.833 => 2
(1)= 或 ==,测试两个值是否相等: x != y
(2)!= 测试不相等: x != y
(3)>: (x > y) = YES
(4)>=: (x >= y) = YES
(5)<: (x < y) = NO
(6)<=: (x <= y) = NO
(1)逻辑或 || : true || false = yes
(2)逻辑与 && : true && false = no
(3)逻辑非 ! : !true = no