控制器由servlet实现,页由freeMark完成。
第一个例子:
test.ftl如下:
<html>
<head>
<title>FreeMarker Example Web Application 1</title>
</head>
<body>
${message}
</body>
</html>
servlet如下:
public class HelloServlet extends HttpServlet {
private Configuration cfg;
public void init() {
cfg = new Configuration();
cfg.setServletContextForTemplateLoading(getServletContext(),
"templates");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Map root = new HashMap();
root.put("message", "Hello World!");
Template t = cfg.getTemplate("test.ftl");
System.out.println(t.getEncoding());//GBK编码
response.setContentType("text/html; charset=" + t.getEncoding());
Writer out = response.getWriter();
try {
t.process(root, out);
} catch (TemplateException e) {
throw new ServletException(
"Error while processing FreeMarker template", e);
}
}
}
web.xml配置如下:
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>com.mengya.servlet.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
测试:
<body>
<a href="hello">FreeMark测试</a>
</body>
第二个例子:(get,set方法省掉,辅助类)
public class Page {
private String template;
private String forward;
private Map root = new HashMap();
}
共同的servlet如下:
public class ControllerServlet extends HttpServlet {
private Configuration cfg;
public void init() {
cfg = new Configuration();
//设置ftl文件加载的路径
cfg.setServletContextForTemplateLoading(getServletContext(),
"templates");
//设置freeMark更新缓存的时间//0表示不用缓存
cfg.setTemplateUpdateDelay(0);
cfg.setTemplateExceptionHandler(TemplateExceptionHandler.HTML_DEBUG_HANDLER);
//设置freeMark的包裹策略
cfg.setObjectWrapper(ObjectWrapper.BEANS_WRAPPER);
cfg.setDefaultEncoding("ISO-8859-1");
cfg.setOutputEncoding("UTF-8");
cfg.setLocale(Locale.US);
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doGet(req, resp);
}
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//URL:http://127.0.0.1:8080/FreeMarkStudy/templates/index.a
//request.getServletPath:/templates/index.a
String action = req.getServletPath();
if (action == null)
action = "index";
if (action.startsWith("/"))
//action = action.substring(1);
action = action.substring(action.lastIndexOf("/")+1);//获得index
if (action.lastIndexOf(".") != -1) {
action = action.substring(0, action.lastIndexOf("."));
}
Method actionMethod;
try {
actionMethod = getClass().getMethod(action + "Action",
new Class[] { HttpServletRequest.class, Page.class });
} catch (NoSuchMethodException e) {
throw new ServletException("Unknown action: " + action);
}
req.setCharacterEncoding(cfg.getOutputEncoding());
Page page = new Page();
try {
actionMethod.invoke(this, new Object[] { req, page });
} catch (IllegalAccessException e) {
throw new ServletException(e);
} catch (InvocationTargetException e) {
throw new ServletException(e.getTargetException());
}
if (page.getTemplate() != null) {
Template t = cfg.getTemplate(page.getTemplate());
resp.setContentType("text/html; charset=" + cfg.getOutputEncoding());
resp.setHeader("Cache-Control",
"no-store, no-cache, must-revalidate, "
+ "post-check=0, pre-check=0");
resp.setHeader("Pragma", "no-cache");
resp.setHeader("Expires", "Thu, 01 Dec 1994 00:00:00 GMT");
Writer out = resp.getWriter();
try {
t.process(page.getRoot(), out);
} catch (TemplateException e) {
throw new ServletException(
"Error while processing FreeMarker template", e);
}
} else if (page.getForward() != null) {
RequestDispatcher rd = req.getRequestDispatcher(page.getForward());
rd.forward(req, resp);
} else {
throw new ServletException("The action didn't specified a command.");
}
}
}
实体Bean如下:(get,set方法省掉)
public class GuestbookEntry {
private String name;
private String email;
private String message;
}
servlet如下:
public class GuestbookServlet extends ControllerServlet {
private ArrayList guestbook = new ArrayList();
public void indexAction(HttpServletRequest req, Page p) {
List snapShot;
synchronized (guestbook) {
snapShot = (List) guestbook.clone();
}
p.put("guestbook", snapShot);
p.setTemplate("index.ftl");
}
public void formAction (HttpServletRequest req, Page p)
throws IOException, ServletException {
p.put("name", noNull(req.getParameter("name")));
p.put("email", noNull(req.getParameter("email")));
p.put("message", noNull(req.getParameter("message")));
List errors = (List) req.getAttribute("errors");
p.put("errors", errors == null ? new ArrayList() : errors);
p.setTemplate("form.ftl");
}
public void addAction (HttpServletRequest req, Page p)
throws IOException, ServletException {
List errors = new ArrayList();
String name = req.getParameter("name");
String email = req.getParameter("email");
String message = req.getParameter("message");
if (isBlank(name)) {
errors.add("You must give your name.");
}
if (isBlank(message)) {
errors.add("You must give a message.");
}
if (errors.isEmpty()) {
if (email == null) email = "";
GuestbookEntry e = new GuestbookEntry(name.trim(), email.trim(), message);
synchronized (guestbook) {
guestbook.add(0, e);
}
p.put("entry", e);
p.setTemplate("add.ftl");
} else {
req.setAttribute("errors", errors);
p.setForward("form.a");
}
}
public static String noNull(String s) {
return s == null ? "" : s;
}
public static boolean isBlank(String s) {
return s == null || s.trim().length() == 0;
}
}
web.xml配置如下:
<servlet>
<servlet-name>guestbook</servlet-name>
<servlet-class>com.mengya.servlet.GuestbookServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>guestbook</servlet-name>
<url-pattern>*.a</url-pattern>
</servlet-mapping>
共同的ftl如下:
<#macro page title>
<html>
<head>
<title>FreeMarker Example Web Application 2 - ${title?html}</title>
<meta http-equiv="Content-type" content="text/html; charset=${.output_encoding}">
</head>
<body>
<h1>${title?html}</h1>
<hr>
<#nested>
<hr>
<table border="0" cellspacing=0 cellpadding=0 width="100%">
<tr valign="middle">
<td align="left">
<i>FreeMarker Example 2</i>
</td>
<td align="right">
<a href="http://freemarker.org"><img src="poweredby_ffffff.png" border=0></a>
</td>
</tr>
</table>
</body>
</html>
</#macro>
页面ftl文件一:index.ftl(做list用)
<#import "/common/common.ftl" as com>
<#escape x as x?html>
<@com.page title="Index">
<a href="form.a">Add new message</a> | <a href="help.html">How this works?</a>
<#if guestbook?size = 0>
<p>No messages.
<#else>
<p>The messages are:
<table border=0 cellspacing=2 cellpadding=2 width="100%">
<tr align=center valign=top>
<th bgcolor="#C0C0C0">Name</th>
<th bgcolor="#C0C0C0">Message</td>
</tr>
<#list guestbook as e>
<tr align=left valign=top>
<td bgcolor="#E0E0E0">${e.name} <#if e.email?length != 0> (<a href="mailto:${e.email}">${e.email}</a>)</#if></td>
<td bgcolor="#E0E0E0">${e.message}</td>
</tr>
</#list>
</table>
</#if>
</@com.page>
add.ftl如下:
<#import "/common/common.ftl" as com>
<#escape x as x?html>
<@com.page title="Entry added">
<p>You have added the following entry to the guestbook:
<p><b>Name:</b> ${entry.name}
<#if entry.email?length != 0>
<p><b>Email:</b> ${entry.email}
</#if>
<p><b>Message:</b> ${entry.message}
<p><a href="index.a">Back to the index page...</a>
</@com.page>
</#escape>
from.ftl如下:
<#import "/common/common.ftl" as com>
<#escape x as x?html>
<@com.page title="Add Entry">
<#if errors?size != 0>
<p><font color=red>Please correct the following problems:</font>
<ul>
<#list errors as e>
<li><font color=red>${e}</font>
</#list>
</ul>
</#if>
<form method="POST" action="add.a">
<p>Your name:<br>
<input type="text" name="name" value="${name}" size=60>
<p>Your e-mail (optional):<br>
<input type="text" name="email" value="${email}" size=60>
<p>Message:<br>
<textarea name="message" wrap="soft" rows=3 cols=60>${message}</textarea>
<p><input type="submit" value="Submit">
</form>
<p><a href="index.a">Back to the index page</a>
</@com.page>
分享到:
相关推荐
在IT行业中,静态页面生成是一种常见的优化网页性能的技术,它将动态内容转化为静态...在实际的Web开发中,这样的技术组合有着广泛的应用场景,尤其适用于内容发布系统、博客平台等对页面加载速度有较高要求的项目。
逻辑与:&& 逻辑或:|| 逻辑非:! 逻辑运算符只能作用于布尔值,否则将产生错误 1.9 内建函数 FreeMarker还提供了一些内建函数来转换输出,可以在任何变量后紧跟?,?后紧跟内建函数,就可以通过内建函数来轮换输出...
基于openocd开源工具实现的C#桌面应用工具
精品-2025人工智能神经网络基本原理解析.pdf
施耐德ATV312变频器通过MCGS RTU通讯实现双机监控与控制的触摸屏集成解决方案,无PLC的施耐德ATV312变频器通讯示例:触摸屏控制监控两台变频器,功能多且省成本,改进型可调整步长 P&O MPPT(二区MPPT复现),光储系统MPPT 直流负载供电的单级离网光伏系统中,降压转器将太阳能光伏阵列和直流负载连接起来,同时确保最大功率点跟踪(MPPT) 和电池充电控制的良好运行。 在MPPT方面,提出了一种改进的自适应步长扰动观测(P&O)方法,以达到不同天气条件下太阳能光伏阵列的实际最大功率点(MPP),同时减少稳态振荡和功率损耗。 此外,电池充电控制侧使用三级充电控制器 (TSCC) 为铅酸电池站充电。 ,改进型P&O; 复现二区MPPT; 光储系统MPPT; 最大功率点跟踪(MPPT); 步长扰动观测; 降压转换器; 太阳能光伏阵列; 电池充电控制; 三级充电控制器(TSCC); 铅酸电池站。,改进型P&O MPPT技术,光储系统高效能量管理
redis学习脑图笔记
大学生创业项目源码
Spring Boot企业员工管理系统(包含万字论文+MYSQL)
对应博客地址:https://blog.csdn.net/u011561335/article/details/146312389
相关文章:https://blog.csdn.net/liu_23yanfeng/article/details/146319189
从春晚看科技技术-陈雄 - 公开版本.pptx
在计算机上安装制造装备物联及生产管理ERP系统软件来发挥其高效地信息处理的作用,可以规范信息管理流程,让管理工作可以系统化和程序化,同时,制造装备物联及生产管理ERP系统的有效运用可以帮助管理人员准确快速地处理信息。 制造装备物联及生产管理ERP系统在对开发工具的选择上也很慎重,为了便于开发实现,选择的开发工具为Eclipse,选择的数据库工具为Mysql。以此搭建开发环境实现制造装备物联及生产管理ERP系统的功能。其中管理员管理用户,新闻公告。 制造装备物联及生产管理ERP系统是一款运用软件开发技术设计实现的应用系统,在信息处理上可以达到快速的目的,不管是针对数据添加,数据维护和统计,以及数据查询等处理要求,制造装备物联及生产管理ERP系统都可以轻松应对。 关键词:制造装备物联及生产管理ERP系统;SpringBoot框架,系统分析,数据库设计
传统信息的管理大部分依赖于管理人员的手工登记与管理,然而,随着近些年信息技术的迅猛发展,让许多比较老套的信息管理模式进行了更新迭代,问卷信息因为其管理内容繁杂,管理数量繁多导致手工进行处理不能满足广大用户的需求,因此就应运而生出相应的问卷调查系统。 本问卷调查系统分为管理员还有用户两个权限,管理员可以管理用户的基本信息内容,可以管理新闻资讯信息以及新闻资讯的租赁信息,能够与用户进行相互交流等操作,用户可以查看问卷信息,可以查看新闻资讯以及查看管理员回复信息等操作。 该问卷调查系统采用的是WEB应用程序开发中最受欢迎的B/S三层结构模式,使用占用空间小但功能齐全的MySQL数据库进行数据的存储操作,系统开发技术使用到了JSP技术。该问卷调查系统能够解决许多传统手工操作的难题,比如数据查询耽误时间长,数据管理步骤繁琐等问题。总的来说,问卷调查系统性能稳定,功能较全,投入运行使用性价比很高。 关键词:问卷调查系统;MySQL数据库;SSM技术
VID20250317191237.mp4
西门子S7-1511 PLC PID控制阀门开度与模拟量转换——博途WinCC监控画面程序实践,西门子S7-1511 PLC PID控制阀门开度与模拟量转换——博途WinCC监控画面程序实践,matlab验证码识别系统,基于数字图像处理实现。 经过对图像的预处理、二值化、区域剪裁、数字定位、模板匹配法识别数字。 有gui界面和测试图像数据集。 ,核心关键词:Matlab验证码识别系统; 数字图像处理; 图像预处理; 二值化; 区域剪裁; 数字定位; 模板匹配法识别; GUI界面; 测试图像数据集。,基于Matlab的数字图像处理验证码识别系统
内容概要:本文提供了详细的 VMware 虚拟机安装指南,涵盖软件选择(Pro 和 Player 版区别)、安装步骤(适用于 Windows 和 Linux 主机系统)、虚拟机创建以及操作系统安装指导。详细介绍了配置虚拟机的各项关键设置,如资源分配、硬件参数定制、安装 VMware Tools 提升虚拟机性能和稳定性。并且列出了快照、克隆等高级功能的具体应用,还包括共享文件夹配置和几种常见错误的排除解决方案。 适合人群:初次接触虚拟化的用户和对虚拟环境搭建有一定兴趣的技术爱好者。 使用场景及目标:帮助用户快速部署自己的虚拟机,并掌握虚拟环境中常见的配置技巧,能够针对具体应用场景灵活地调整虚拟机的相关参数,提高工作效率,满足测试、学习、开发的需求。 其他说明:提供了一些安装过程可能遇到的问题及对应解决方案,在创建和维护过程中给予指导性的意见来确保用户的使用体验尽可能顺畅无阻,并给出了部分性能优化建议。
Matlab开发初学者视频教程,零基础入门,非常适合初学者。
质子交换膜燃料电池(PEMFC)Simulink模型:静态与动态模型分析及参数计算,基于Simulink的质子交换膜燃料电池模型:静态和动态模拟,计算输出和效率,cst仿真超表面 极化复用 ,核心关键词: 1. CST仿真 2. 超表面 3. 极化复用 以上信息以分号隔开,即为“CST仿真;超表面;极化复用”。,CST仿真超表面极化复用技术