Velocity 的应用示例

Topas——基于Geant4的放射治疗蒙特卡罗算法模拟工具 本文内容参考Joseph Perl 的线上会议,视频详情可见于,该视频会议内容主要介绍Topas功能、软件架构、工作流程、参数设定、物理模型、具体案例等,对TOPAS的基本入门使用方法以及使用规定作出阐述。 阅读详情
<script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> </script> Velocity 的应用示例  关键字:Java, JSP, Servlet, template, 模板, Apache, Jakarta, Velocity 读者要求:了解 Java Servlet 基本概念  Velocity 是一个基于 Java 的通用模板工具,来自于 jakarta.apache.org 。 Velocity 的介绍请参考 Velocity -- Java Web 开发新技术。这里是它的一个应用示例。 这个例子参照了 PHP-Nuke 的结构, 即所有 HTTP 请求都以 http://www.some.com/xxx/Modules?name=xxx&arg1=xxx&bbb=xxx 的形式进行处理。例子中所有文件都是 .java 和 .html , 没有其他特殊的文件格式。除了 Modules.java 是 Java Servlet, 其余的 .java 文件都是普通的 Java Class. 所有 HTTP 请求都通过 Modules.java 处理。Modules.java 通过 Velocity 加载 Modules.htm。 Modules.htm 有页头,页脚,页左导航链接,页中内容几个部分。其中页头广告、页中内容是变化部分。页头广告由 Modules.java 处理,页中内容部分由 Modules.java dispatch 到子页面类处理。 1) Modules.java import javax.servlet.*; import javax.servlet.http.*; import org.apache.velocity.*; import org.apache.velocity.context.*; import org.apache.velocity.exception.*; import org.apache.velocity.servlet.*; import commontools.*; public class Modules   extends VelocityServlet {   public Template handleRequest(HttpServletRequest request,                  HttpServletResponse response,                  Context context) {     //init     response.setContentType("text/html; charset=UTF-8");     response.setCharacterEncoding("utf-8");     //prepare function page     ProcessSubPage page = null;     ProcessSubPage mainPage = new HomeSubPage();     String requestFunctionName = (String) request.getParameter("name");     boolean logined = false;     String loginaccount = (String) request.getSession(true).getAttribute(       "loginaccount");     if (loginaccount != null) {       logined = true;     }     //default page is mainpage     page = mainPage;     if (requestFunctionName == null||requestFunctionName.equalsIgnoreCase("home")) {       page = mainPage;     }     //no login , can use these page     else if (requestFunctionName.equalsIgnoreCase("login")) {       page = new LoginProcessSubPage();     }     else if (requestFunctionName.equalsIgnoreCase("ChangePassword")) {       page = new ChangePasswordSubPage();     }     else if (requestFunctionName.equalsIgnoreCase("ForgetPassword")) {       page = new ForgetPassword();     }     else if (requestFunctionName.equalsIgnoreCase("about")) {       page = new AboutSubPage();     }     else if (requestFunctionName.equalsIgnoreCase("contact")) {       page = new ContactSubPage();     }     //for other page, need login first     else if (logined == false) {       page = new LoginProcessSubPage();     }     else if (requestFunctionName.equalsIgnoreCase("listProgram")) {       page = new ListTransactionProgramSubPage();     }     else if (requestFunctionName.equalsIgnoreCase(       "ViewProgramItem")) {       page = new ViewTransactionProgramItemSubPage();     }     else if (requestFunctionName.equalsIgnoreCase(       "UpdateProgramObjStatus")) {       page = new UpdateTransactionProgramObjStatusSubPage();     }     else if (requestFunctionName.equalsIgnoreCase(       "Search")) {       page = new SearchSubPage();     }     //check if this is administrator     else if (Utilities.isAdministratorLogined(request)) {       //Utilities.debugPrintln("isAdministratorLogined : true");       if (requestFunctionName.equalsIgnoreCase("usermanagement")) {         page = new UserManagementSubPage();       }       else if (requestFunctionName.equalsIgnoreCase(         "UploadFiles")) {         page = new UploadFilesSubPage();       }       else if (requestFunctionName.equalsIgnoreCase(         "DownloadFile")) {         page = new DownloadFileSubPage();       }       else if (requestFunctionName.equalsIgnoreCase(         "Report")) {         page = new ReportSubPage();       }     }     else {       //no right to access.       //Utilities.debugPrintln("isAdministratorLogined : false");       page = null;     }     //Utilities.debugPrintln("page : " page.getClass().getName());     if(page != null){       context.put("function_page",             page.getHtml(this, request, response, context));     }else{       String msg = "Sorry, this module is for administrator only.You are not administrator.";       context.put("function_page",msg);     }          context.put("page_header",getPageHeaderHTML());     context.put("page_footer",getPageFooterHTML());     Template template = null;     try {       template = getTemplate("/templates/Modules.htm"); //good     }     catch (ResourceNotFoundException rnfe) {       Utilities.debugPrintln("ResourceNotFoundException 2");       rnfe.printStackTrace();     }     catch (ParseErrorException pee) {       Utilities.debugPrintln("ParseErrorException2 " pee.getMessage());     }     catch (Exception e) {       Utilities.debugPrintln("Exception2 " e.getMessage());     }     return template;   }   /**    * Loads the configuration information and returns that information as a Properties, e    * which will be used to initializ the Velocity runtime.    */   protected java.util.Properties loadConfiguration(ServletConfig config) throws     java.io.IOException, java.io.FileNotFoundException {     return Utilities.initServletEnvironment(this);   } } 2) ProcessSubPage.java , 比较简单,只定义了一个函数接口 getHtml import javax.servlet.http.*; import org.apache.velocity.context.*; import org.apache.velocity.servlet.*; import commontools.*; public abstract class ProcessSubPage implements java.io.Serializable {   public ProcessSubPage() {   }   public String getHtml(VelocityServlet servlet, HttpServletRequest request,              HttpServletResponse response,              Context context) {     Utilities.debugPrintln(       "you need to override this method in sub class of ProcessSubPage:"        this.getClass().getName());     return "Sorry, this module not finish yet.";   } } 他的 .java 文件基本上是 ProcessSubPage 的子类和一些工具类。 ProcessSubPage 的子类基本上都是一样的流程, 用类似 context.put("page_footer",getPageFooterHTML()); 的写法置换 .html 中的可变部分即可。如果没有可变部分,完全是静态网页,比如 AboutSubPage, 就更简单。 3) AboutSubPage.java import org.apache.velocity.servlet.VelocityServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.velocity.context.Context; public class AboutSubPage extends ProcessSubPage {   public AboutSubPage() {   }   public String getHtml(VelocityServlet servlet, HttpServletRequest request,              HttpServletResponse response, Context context) {     //prepare data     //context.put("xxx","xxxx");                            Template template = null;     String fileName = "About.htm";     try {       template = servlet.getTemplate(fileName);       StringWriter sw = new StringWriter();       template.merge(context, sw);       return sw.toString();     }     catch (Exception ex) {       return "error get template " fileName " " ex.getMessage();     }   } } 其他 ProcessSubPage 的子类如上面基本类似,只不过会多了一些 context.put("xxx","xxxx") 的语句。 通过以上的例子,我们可以看到,使用 Velocity Servlet , 所有的代码为: 1 个 java serverlet m 个 java class n 个 Html 文件。 这里是用了集中处理,然后分发(dispatch)的机制。不用担心用户在没有登陆的情况下访问某些页面。用户验证,页眉页脚包含都只写一次,易于编写、修改和维护。代码比较简洁,并且很容易加上自己的页面缓冲功能。可以随意将某个页面的 html 在内存中保存起来,缓存几分钟,实现页面缓冲功能。成功、出错页面也可以用同样的代码封装成函数,通过参数将 Message/Title 传入即可。 因为 Java 代码与 Html 代码完全在不同的文件中,美工与java代码人员可以很好的分工,每个人修改自己熟悉的文件,基本上不需要花时间做协调工作。而用 JSP, 美工与java代码人员共同修改维护 .jsp 文件,麻烦多多,噩梦多多。而且这里没有用 xml ,说实话,懂 xml/xls 之类的人只占懂 Java 程序员中的几分之一,人员不好找。 因为所有 java 代码人员写的都是标准 Java 程序,可以用任何 Java 编辑器,调试器,因此开发速度也会大大提高。美工写的是标准 Html 文件,没有 xml, 对于他们也很熟悉,速度也很快。并且,当需要网站改版的时候,只要美工把 html 文件重新修饰排版即可,完全不用改动一句 java 代码。 爽死了!! 4) 工具类 Utilities.java import java.io.*; import java.sql.*; import java.text.*; import java.util.*; import java.util.Date; import javax.naming.*; import javax.servlet.*; import javax.servlet.http.*; import org.apache.velocity.*; import org.apache.velocity.app.*; import org.apache.velocity.context.Context; import org.apache.velocity.servlet.*; public class Utilities {   private static Properties m_servletConfig = null;   private Utilities() {   }   static {     initJavaMail();   }   public static void debugPrintln(Object o) {     String msg = "proj debug message at " getNowTimeString()       " ------------- ";     System.err.println(msg o);   }   public static Properties initServletEnvironment(VelocityServlet v) {     // init only once     if (m_servletConfig != null) {       return m_servletConfig;     }     //debugPrintln("initServletEnvironment....");     try {       /*        * call the overridable method to allow the        * derived classes a shot at altering the configuration        * before initializing Runtime        */       Properties p = new Properties();       ServletConfig config = v.getServletConfig();       // Set the Velocity.FILE_RESOURCE_LOADED_PATH property       // to the root directory of the context.       String path = config.getServletContext().getRealPath("/");       //debugPrintln("real path of / is : " path);       p.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, path);       // Set the Velocity.RUNTIME_LOG property to be the file       // velocity.log relative to the root directory       // of the context.       p.setProperty(Velocity.RUNTIME_LOG, path              "velocity.log"); // Return the Properties object. //return p;       Velocity.init(p);       m_servletConfig = p;       return p;     }     catch (Exception e) {       debugPrintln(e.getMessage());       //throw new ServletException("Error initializing Velocity: " e);     }     return null;     //this.getServletContext().getRealPath("/");   }   private static void initJavaMail() {   }   public static Connection getDatabaseConnection() {     Connection con = null;     try {       InitialContext initCtx = new InitialContext();       javax.naming.Context context = (javax.naming.Context) initCtx.         lookup("java:comp/env");       javax.sql.DataSource ds = (javax.sql.DataSource) context.lookup(         "jdbc/TestDB");       //Utilities.debugPrintln("ds = " ds);       con = ds.getConnection();     }     catch (Exception e) {       Utilities.debugPrintln("Exception = " e.getMessage());       return null;     }     //Utilities.debugPrintln("con = " con);     return con;   }   public static java.sql.ResultSet excuteDbQuery(Connection con, String sql,     Object[] parameters) {     //Exception err = null;     //Utilities.debugPrintln("excuteDbQuery" parameters[0] " ,sql=" sql);     try {       java.sql.PreparedStatement ps = con.prepareStatement(sql);       for (int i = 0; i < parameters.length; i ) {         processParameter(ps, i 1, parameters[i]);       }       return ps.executeQuery();     }     catch (Exception e) {       //Utilities.debugPrintln(e.getMessage());       e.printStackTrace();     }     return null;   }   public static void excuteDbUpdate(String sql, Object[] parameters) {     Connection con = Utilities.getDatabaseConnection();     excuteDbUpdate(con, sql, parameters);     closeDbConnection(con);   }   public static void excuteDbUpdate(Connection con, String sql,                    Object[] parameters) {     Exception err = null;     try {       java.sql.PreparedStatement ps = con.prepareStatement(sql);       for (int i = 0; i < parameters.length; i ) {         processParameter(ps, i 1, parameters[i]);       }       ps.execute();     }     catch (Exception e) {       err = e;       //Utilities.debugPrintln(err.getMessage());       e.printStackTrace();     }   }   private static void processParameter(java.sql.PreparedStatement ps,                      int index, Object parameter) {     try {       if (parameter instanceof String) {         ps.setString(index, (String) parameter);       }       else {         ps.setObject(index, parameter);       }     }     catch (Exception e) {       //Utilities.debugPrintln(e.getMessage());       e.printStackTrace();     }   }   public static void closeDbConnection(java.sql.Connection con) {     try {       con.close();     }     catch (Exception e) {       Utilities.debugPrintln(e.getMessage());     }   }   public static String getResultPage(     String title, String message, String jumpLink,     VelocityServlet servlet, HttpServletRequest request,     HttpServletResponse response, Context context) {     Template template = null;     context.put("MessageTitle", title);     context.put("ResultMessage", message);     context.put("JumpLink", jumpLink);     try {       template = servlet.getTemplate(         "/templates/Message.htm");       StringWriter sw = new StringWriter();       template.merge(context, sw);       return sw.toString();     }     catch (Exception ex) {       return "error get template Message.htm " ex.getMessage();     }   }   public static String mergeTemplate(String fileName, VelocityServlet servlet,                     Context context) {     Template template = null;     try {       template = servlet.getTemplate(fileName);       StringWriter sw = new StringWriter();       template.merge(context, sw);       return sw.toString();     }     catch (Exception ex) {       return "error get template " fileName " " ex.getMessage();     }   } }
基于STM32的最简易蓝牙遥控小车 基于STM32的蓝牙遥控小车,基于HAL库编写代码,具有移动功能,读者可自行添加其他扩展功能。按下状态的对应关系:2前进,4左转,5停止,6右转,8后退,松开状态都是5,都选择16进制。首先按照小车的图纸把小车的机械部分装好。做这个小车的成本在200元左右,包括焊接设备,杜邦线等。 阅读详情

相关推荐

Ubuntu下OpenOCD+GDB的安装、编译及使用

目标开发板(芯片):stm32mp157aaa 仿真器:ST-Link 操作系统:Ubuntu 18.04 调试软件:OpenOCD OpenOCD的安装 首先下载OpenOCD有多种方式,可以GitHub上下载,目录下打开终端,输入 git clone git://git.code.sf.net/p/openocd/code openocd 下载完整的OpenOCD的文件夹。进入到OpenOCD的目录下,开始安装。 接着,OpenOCD适用于微处理器的debug和烧写,需要下载相关库 sud

蓝冰露的博客 9525

Velocity使用示例

本文介绍了Velocity的使用示例

快乐江小鱼的博客 365

Oracle 11g RAC 节点通信故障排查与修复指南

本文详细介绍了Oracle 11g RAC集群发生节点通信故障时的系统性排查与修复方法。当出现节点异常重启时,核心问题往往源于心跳网络中断。文章提供了从快速诊断、日志分析到六层深度检查的完整指南,并给出了针对网络配置、内核参数及Oracle已知Bug等常见根因的实战解决方案,帮助DBA快速恢复集群稳定。

weixin_29246195的博客 281

Velocity入门教程一

简介Velocity是一个基于JAVA的模板引擎,使用这个工具你可以很容易地创建和渲染你所要展示的格式化文档。 官网定义: Velocity is a Java-based template engine, a simple and powerful development tool that allows you to easily create and render documents

u014133299的博客 931

Cadence IC617仿真实践:有源电流镜的共模抑制比优化策略

本文基于Cadence IC617平台,详细介绍了有源电流镜共模抑制比(CMRR)的仿真与优化全流程。从电路搭建、DC工作点分析到AC仿真获取差模/共模增益,逐步解析CMRR计算方法。核心优化策略包括提升电流镜输出阻抗、优化差分对匹配性及调整晶体管尺寸,并探讨了与电源抑制比(PSRR)的权衡,为模拟集成电路设计提供实用指南。

weixin_29313817的博客 184

视觉语言模型对抗攻击与防御:从传统方法到多模态挑战

本文深入探讨了视觉语言模型(VLM)面临的对抗攻击与防御挑战,从传统单模态攻击到多模态威胁的演进。分析了包括FGSM、PGD等经典攻击方法,以及新兴的多模态攻击如跨模态对抗样本和越狱攻击。同时提出了跨模态一致性检查、动态防御机制等创新防御策略,并结合医疗影像诊断等实战案例,为提升AI系统安全性提供了重要见解。

weixin_29231725的博客 393

Velocity示例

[size=xx-large][color=orange][b]Velocity示例[/b][/color][/size] HelloController.java类: [size=medium][b][color=red]示例01:[/color][/b][/size] [code="java"] package com.xiaonei.rose.gettingStarted.con...

mohaiyong的专栏 237

关于LIO-SAM编译时出现错误 /usr/bin/ld: 找不到 -lBoost::timer

关于LIO-SAM编译时出现错误: 下载LIO-SAM代码 进入LIO-SAM文件夹,通过以下代码编译: mkdir build cd build cmake .. make 报错: /usr/bin/ld: 找不到 -lBoost::timer collect2: error: ld returned 1 exit status CMakeFiles/lio_sam_imuPreintegration.dir/build.make:759: recipe for target 'devel/lib/li

wwtx的博客 3648

一、什么是Velocity及简单示例

1、velocity简介:  velocity是一个java模板引擎技术,任何人可以使用这种简单而又强有力的模板语言去获取java对象。  在使用Velocity进行web开发时,web开发人员和java程序员可以同时根据Model-View-Controller(MVC)模型,进行网站开发,这也意味着web开发人员可以纯粹的专注于创建看起来好看的网页而程序员可专门编写完美的代码。...

aan3237的博客 765

小波变换(深入浅出)

小波变换

weixin_46713695的博客 3万+

13、7自由度机械臂混合逆运动学算法解析

本文介绍了一种针对7自由度机械臂的混合逆运动学算法,通过引入额外参数Φ解决冗余自由度问题,并实现了避障、避免关节超限和扩大工作空间。该方法采用解析逆运动学求解策略,克服了机械臂在奇异位姿时的配置不连续性问题。通过对比实验验证了该算法在腕部关节角度连续性和位姿可达性方面的优越性,同时结合躯干逆运动学显著扩展了机械臂的工作空间。

rgv23456789的博客 237

Tiny模板引擎(Velocity Plus)应用示例

目录[-]宏的可变参数 Set示例宏定义及其调用示例宏定义及其调用进阶示例宏定义及其调用之嵌套定义Tiny模板中的内容显示Tiny模板之注释Tiny模板引擎强制不解析标记Tiny模板引擎之IFTiny模板语言之循环Tiny模板引擎之布局Tiny模板引擎之调用宏的N种写法Tiny模板引擎之宏默认值Tiny模板引擎之格式严格控制如何快速编写并运行Tiny模板Tiny模板引擎之配套开发工具特性介绍截...

TINY框架 419

安装并新建windows下wxwroks7.0 bootrom工程

安装licence,将zwrsLicense-vx7-perm.lic粘贴到安装目录C盘WindRiver/license下。现在双击Workbench 4,新建vxworks7.0工程,会出现下面的情况,因为没有licence。编译完成binaries下生成wxwroks x86格式,可以修改bootrom硬件信息的配置了。单击x86_wxwroks工程右键,build project编译工程。双击桌面Workbench 4打开,新建windows下工程。新建完成,选择finish。

wangjie36的博客 1923

Velocity资源

2019独角兽企业重金招聘Python工程师标准>>> ...

weixin_34033624的博客 180

OV9734 DATASHEET,完整规格书

OV9734完整规格书,包括电气参数,尺寸规格,寄存器配置表等

华为的C语言编程规范.pdf

华为技术有限公司内部技术规范。本规范制定了编写C语言程序的基本原则、规则和建议。从代码的清晰、简洁、可测试、安全、程序效率、可移植各个方面对C语言编程作出了具体指导。

Velocity入门之基础语法

1. 变量 (1)变量的定义: #set($name = "hello") 说明:velocity中变量是弱类型的。 当使用#set 指令时,括在双引号中的字面字符串将解析和重新解释,如下所示: #set($directoryRoot = "www" ) #set($templateName = "index.vm" ) #set($template = "$dire...

u011833515的专栏 210

VB摄像头监控

该VB模块可对摄像头捕获的画面进行录像等,可在创建的窗口进行控制

Velocity实例

Velocity 是一个基于 Java 的通用模板工具,来自于 jakarta.apache.org 。 Velocity 的介绍请参考 Velocity -- Java Web 开发新技术。这里是它的一个应用示例。这个例子参照了 PHP-Nuke 的结构, 即所有 HTTP 请求都以 http://www.some.com/xxx/Modules?name=xxx&arg1=xxx&bbb=xx

joy的专栏 1429

VC中sqlite的使用

在VC中对sqlite的使用,实现数据库大批数据的快速插入,读取数据库中的数据在ListCtrl中显示

Velocity 入门之 HelloWorld

Velocity 是如何工作的呢? 虽然大多 Velocity 的应用都是基于 Servlet 的网页制作。但是为了说明 Velocity 的使用,我决定采用更通用的 Java application 来说明它的工作原理。    似乎所有语言教学的开头都是采用 HelloWorld 来作为第一个程序的示例。这里也不例外。  01 package com.mak

caomiao2006的专栏 953

velocity入门示例

<br /><br /> <br />下面是一个简单的实例:<br /> <br />java代码:<br /> <br />package com.ali.vm;<br /> <br />import java.io.StringWriter;<br />import java.math.BigDecimal;<br />import java.util.Date;<br /> <br />import org.apache.velocity.app.VelocityEngine;<br />import

天涯行客 881

Velocity入门到精通(上篇)

Velocity是一个基于Java的模板引擎,可以通过特定的语法获取在java对象的数据 , 填充到模板中,从而实现界面和java代码的分离!Velocity Template Language (VTL) , 是Velocity 中提供的一种模版语言 , 旨在提供最简单和最干净的方法来将动态内容合并到网页中。简单来说VTL可以将程序中的动态数展示到网页中注释非解析内容引用和指令。

我有一张床的博客 2万+

velocity入门(二)

2019独角兽企业重金招聘Python工程师标准>>> ...

weixin_34337381的博客 74
上一篇: 将脚本语言加进你的程序中
下一篇: J2me的基本概念
java169
博客等级 码龄19年 27粉丝 2568原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值