velocity模板实战
场景:json配置报文转换
遇到的问题:1.json报文转换成map,多节点如何处理?数组如何处理?
2.velocity模板处理数组
3.应用之间rabbitmq通讯map反序列化,数组报错?
知识点:
HashMap map中重要的两个方法map.containsKey()和map.contaisValue()
#foreach($key in [0..10])
$key
#end
#if($id == "")
#end
计数器 velocityCount
haspmap的属性可以在模板中使用
样例报文
{
"service":{
"service_header":{
"name":"张三",
"age":"12"
}
"service_body":{
"info":[
{
"address":"上海",
"tel":"111"
},
{
"address":"北京",
"tel":"020"
}
]
}
}
}
模板配置
{
"service":{
"service_header":{
"lastname":"${name}",
"age":"${age}"
}
"service_body":{
"info":[
#set($infos={"address":"address","telphone":"tel"})
#foreach($key in ${infos})
{
#foreach($key2 in $key.keySet())
#foreach($key3 in $infos.keySet())
#if($key2 == $infos.get($key3))
"$key3":"$key.get($key2)"
#if($velocityCount != $key.size())
,
#end
#end
#end
#end
}
#if($velocityCount != $infos.size())
,
#end
#end
]
}
}
}
测试代码
package com.sunline.nfs.process; import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.StringWriter;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Properties; import net.sf.json.JSONArray;
import net.sf.json.JSONObject; import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource; public class velocityEngine {
static Map<String,Object> jsonMap = new LinkedHashMap<String,Object>(); public static Map recursinMap(Map<String,Object> map){
net.sf.json.JSONObject jObject = new net.sf.json.JSONObject();
for(String key:map.keySet()){
String str = map.get(key).toString();
if(str.startsWith("{")){
/*com.alibaba.fastjson.JSONObject jObject = JSON.parseObject(str);*/
Map<String,Object> map2 = jObject.fromObject(str);
if(!map.toString().endsWith(map2.toString()+"}")){
int i = map.toString().indexOf(map2.toString())+1;
String value ="{" + map.toString().substring((i+map2.toString().length()),map.toString().length());
map2.put(key, value);
}
return recursinMap(map2);
}
else{
if(str.startsWith("[")){
JSONArray tmpMaps = JSONArray.fromObject(str);
System.out.println("key="+key+" tmpMaps"+tmpMaps);
jsonMap.put(key, tmpMaps);
/*for(int i=0;i<tmpMaps.size();i++){
JSONObject job = tmpMaps.getJSONObject(i);
Map<String,Object> jobMap = JSONObject.fromObject(job.toString());
for(String key2:jobMap.keySet())
jsonMap.put(key+i+key2, jobMap.get(key2));
} */
}
else{
jsonMap.put(key, str);
} }
}
return jsonMap;
}
@SuppressWarnings("null")
public static void main(String[] args) throws IOException{
String filename = "ObtainAppNo.txt";
String json = readJson(filename);
net.sf.json.JSONObject jObject = new net.sf.json.JSONObject();
Map<String,Object> map2 = jObject.fromObject(json);
Map<String,Object> jsonMap = recursinMap(map2);
System.out.println("-----" +jsonMap);
//初始化参数
Properties properties=new Properties();
//设置velocity资源加载方式为class
properties.setProperty("resource.loader", "class");
//设置velocity资源加载方式为file时的处理类
properties.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
//实例化一个VelocityEngine对象
VelocityEngine velocityEngine=new VelocityEngine(properties); //实例化一个VelocityContext
VelocityContext context=new VelocityContext();
for(Object key :jsonMap.keySet()){
context.put((String)key, jsonMap.get(key));
}
//实例化一个StringWriter
StringWriter writer=new StringWriter();
//假若在com.velocity.test包下有一个hello.vm文件,那么加载路径为com/velocity/test/hello.vm
// String json2 = readJson("2.txt");
// velocityEngine.mergeTemplate(json2, "gbk", context, writer);
//这种方式是正确的
velocityEngine.mergeTemplate("2.txt", "gbk", context, writer);
String str = writer.toString();
str = str.replaceAll("\\s*", "");
System.out.println("-----" +str); }
public static String readJson(String filename){
Resource resource =new ClassPathResource(filename);
File file;
try {
file = resource.getFile();
BufferedReader reader= new BufferedReader(new FileReader(file));
String temp=null;
String str="";
while((temp=reader.readLine())!=null){
str = str + temp;
}
str=str.replace(" ", "");
return str;
} catch (IOException e) {
e.printStackTrace();
} return null;
} }
velocity模板实战的更多相关文章
- velocity模板引擎学习(4)-在standalone的java application中使用velocity及velocity-tools
通常velocity是配合spring mvc之类的框架在web中使用,但velocity本身其实对运行环境没有过多的限制,在单独的java application中也可以独立使用,下面演示了利用ve ...
- velocity模板引擎学习(3)-异常处理
按上回继续,前面写过一篇Spring MVC下的异常处理.及Spring MVC下的ajax异常处理,今天看下换成velocity模板引擎后,如何处理异常页面: 一.404错误.500错误 <e ...
- Velocity模板引擎语法
Velocity 模板引擎介绍 Velocity是一个基于java的模板引擎(template engine).它允许任何人仅仅简单的使用模板语言(template language)来引用由java ...
- java 利用spring JavaMailSenderImpl发送邮件,支持普通文本、附件、html、velocity模板
java 利用spring JavaMailSenderImpl发送邮件,支持普通文本.附件.html.velocity模板 博客分类: Java Spring 本文主要介绍利用JavaMailS ...
- velocity模板使用建议
复杂页面前端模块化的方式: 方式一:iframe 方式二:velocity模板(#parse) 方式一,优点很多,也有缺点,例如页面之间传递参数等: 方式二,页面之间的调用,传参更容易,页面性能更好: ...
- Velocity模板引擎入门
类似于PHP中的Smarty,Velocity是一个基于Java的模板引擎(template engine).它允许任何人仅仅简单的使用模板语言(template language)来引用由java代 ...
- 【转】Velocity模板(VM)语言介绍
http://www.blogjava.net/caizh2009/archive/2010/08/20/329495.html Velocity是什么? Velocity是一个基于java的模板引擎 ...
- 【转载】Velocity模板引擎的介绍和基本的模板语言语法使用
原文地址http://www.itzhai.com/the-introduction-of-the-velocity-template-engine-template-language-syntax- ...
- 使用 Velocity 模板引擎快速生成代码(zhuan)
http://www.ibm.com/developerworks/cn/java/j-lo-velocity1/ ****************************************** ...
随机推荐
- Mybatis注解开发模糊查询
Mybatis注解开发模糊查询 一般在使用mybatis时都是采用xml文件保存sql语句 这篇文章讲一下在使用mybatis的注解开发时,如何进行模糊查询 模糊查询语句写法(在@Select注解中) ...
- pycharm虚拟环境
pycharm虚拟环境 1. 选择一个本地的空目录,---该目录就作为python虚拟环境目录, 2. 选择本地python安装目录: 3. 勾选该选项后则可以使用base interpreter中的 ...
- php+layui实现图片上传与预览
端代码: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <titl ...
- ubuntu 18.04 设置固定ip
# This file is generated from information provided by # the datasource. Changes to it will not pers ...
- Ubuntu16.04.2 LTS下使用编译安装程序(使用configure、make、 make install)
以安装vim为例. (vim 是vi的升级版本,它不仅兼容vi的所有指令,而且还有一些新的特性在里面). 1.获取源文件 首先进入/usr/local下(只是为了方便处理安装文件,位置随意) 用git ...
- X86和X64环境下的基本类型所占用的字节大小
同样的程序代码,使用Visual Studio 进行编译,当目标平台分别为x86或x64环境时,其编译结果是不同的.在x86环境下,指针都是4个字节的:而在x64环境下,指针都是8字节的.测试代码如下 ...
- 在Silverlight中动态绑定页面报表(PageReport)的数据源
ActiveReports 7中引入了一种新的报表模型——PageReport(页面布局报表),这种报表模型又细分了两种具体显示形式: o 固定页面布局报表模型(FPL)是ActiveRepor ...
- Android学习 -- Activity 以及Activity之间值传递
项目结构如图 关键代码如下 strings.xml文件代码如下: <?xml version="1.0" encoding="utf-8"?> &l ...
- 关于MSCOMM.OCX无法正常注册的问题解决
[问题] 关于“Component'MSCOMM32.OCX'or one of its dependencies not correctly registered: afole is missing ...
- Eclipse无法自动编译生成class文件
在Maven项目中,通常eclipse生成的class文件都会在target/classes文件夹下,但是有时候由于各种原因,classes下没有生成class文件,导致项目启动失败 . 大部分cla ...