定义一个主方法的类
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
public class VelocityMain {
//模板文件数组定义:顺序是你自己的
static String[] templateName = {
"domain.js", "domain.jsp", "DomainController.java"
, "DomainQuery.java", "DomainServiceImpl.java", "IDomainService.java"
};
//项目路径:
static final String jsFilePath = "E:/java/ideaProject/Management/mg-web/src/main/webapp/static/js/model/";
static final String jspFilePath = "E:/java/ideaProject/Management/mg-web/src/main/webapp/WEB-INF/views/";
static final String controllerFilePath = "E:/java/ideaProject/Management/mg-web/src/main/java/cn//web/controller/";
static final String queryFilePath = "E:/java/ideaProject/Management/mg-common/src/main/java/cn//query/";
static final String serviceImplFilePath = "E:/java/ideaProject/Management/mg-service/src/main/java/cn//service/impl/";
static final String serviceFilePath = "E:/java/ideaProject/Management/mg-service/src/main/java/cn//service/";
//生成文件的路径数据定义:这个要和templateName对应起来
static String[] outFileRootPath = {
jsFilePath, jspFilePath, controllerFilePath, queryFilePath
, serviceImplFilePath,serviceFilePath
};
//可能有多个domain需要生成
static String[] domain = {"Datadictionary"};
/**
* 1:定义模板
* 2:使用Velocity生成模板:
* 2.1:初始化Velocity:设置加载方式:classpath下加载
* 2.2:设置Velocity的上下文
* 2.3:从classpath下读取模板,输出到文件
*/
public static void main(String[] args) throws ClassNotFoundException {
for (String domainMame : domain) {
Properties p = new Properties();
// 2.1:初始化Velocity:设置加载方式:classpath下加载
// 使用classpath加载:org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader
p.setProperty(Velocity.RESOURCE_LOADER, "class");
p.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
Velocity.init(p);
//2.2:设置Velocity的上下文
VelocityContext context = new VelocityContext();
String domainLower = domainMame.substring(0, 1).toLowerCase() + domainMame.substring(1);
context.put("Domain", domainMame); //Department
context.put("domain", domainLower); //department
context.put("fieldList",scanDomain(domainMame));
//遍历模板,每一个模板都生成一个文件
for (int i=0;i<templateName.length;i++) {
//2.3:读取模板,输出到文件
//从classpath下读取模板
String tempName = templateName[i];
// i=0==>tempName=domain.js
String templateFile = "template/" + tempName;
// templateFile=template\domain.js
//根据模板的索引读取对应生成文件的路径:
String outFilePath = outFileRootPath[i];
// outFilePath=F:\java0830\itsource-parent\crm-web\src\main\webapp\static\js\
//"F:/java/parent/crm-web/src/main/webapp/WEB-INF/views/";
boolean views= outFilePath.contains("views")||outFilePath.contains("js");
if(views){
// F:/java/parent/crm-web/src/main/webapp/WEB-INF/views/employee/
outFilePath=outFilePath+"/"+domainLower+"/";
}
// outFile=outFilePath+domain.js==>outFilePath+employee.js
String outFile = outFilePath + tempName;
outFile=outFile.replaceAll("Domain",domainMame).replaceAll("domain",domainLower);
try {
File file = new File(outFile);
File parentFile = file.getParentFile();
//文件不存在,就创建
if (!parentFile.exists()) {
parentFile.mkdirs();
}
//文件输出
FileWriter fileWriter = new FileWriter(file);
Template template = Velocity.getTemplate(templateFile, "utf-8");
template.merge(context, fileWriter);
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/* List<FieldVo> voList = scanDomain("Employee");
for (FieldVo fieldVo : voList) {
System.out.println(fieldVo);
}*/
}
private static List<FieldVo> scanDomain(String domainMame) throws ClassNotFoundException {
List<FieldVo> voList=new ArrayList<>();
// domainMame=Employee
// cn.itsource.crm.domain.Employee
String clazzPath="cn.itsource.domain."+domainMame;
Class<?> c = Class.forName(clazzPath);
System.out.println(c);
//获取字段
Field[] declaredFields = c.getDeclaredFields();
for (Field declaredField : declaredFields) {
//判断这个字段上是否有EasyuiColumn
if(declaredField.isAnnotationPresent(EasyuiColumn.class)){
EasyuiColumn easyuiColumn = declaredField.getAnnotation(EasyuiColumn.class);
//获取到注解的title的值
String title = easyuiColumn.title();
String name = declaredField.getName();
FieldVo fieldVo=new FieldVo();
fieldVo.setField(name);
fieldVo.setTitle(title);
voList.add(fieldVo);
}
}
for (FieldVo fieldVo : voList) {
System.out.println(fieldVo);
}
return voList;
}
}
各自需要生成的类
domain.js
$(function () {
//变量的抽取:
var ${domain}Datagrid=$('#${domain}Datagrid'); //employeeDataGrid
var ${domain}Dlg=$('#${domain}Dlg');
var ${domain}Form=$('#${domain}Form');
//datagrid
${domain}Datagrid.datagrid({
url: '${domain}/list',
fit:true,
title:'部门管理',
rownumbers:true,
pagination:true,
singleSelect:true,
toolbar:"#toolbar",
columns: [[
/*使用遍历:遍历的是Velocity中上下文的对象:
* fieldList
* #foreach( $elem in $allElems)
$elem</br>
#end
{field: 'id', title: 'id', width: '10%',align: 'center'},
* */
#foreach( $fieldVo in $fieldList)
{field: '$fieldVo.field', title: '$fieldVo.title', width: '10%',align: 'center'},
#end
]]
});
//按钮的事件
var cmdObj={
'add':function () {
//弹出一个dialog,里面装form表单 ${domain}Dlg
${domain}Dlg.dialog('open').dialog('center').dialog('setTitle','部门添加');
//清空表单
${domain}Form.form('clear');
},
'edit':function () {
//先获取编辑的数据
var row = ${domain}Datagrid.datagrid('getSelected');
//做一个判断:是否选中
if (row){
//弹出dialog,进行数据的回显
//弹出一个dialog,里面装form表单 ${domain}Dlg
${domain}Dlg.dialog('open').dialog('center').dialog('setTitle','部门修改');
//清空表单
${domain}Form.form('clear');
//表单数据的回显:
${domain}Form.form('load',row);
}else{
$.messager.alert('温馨提示','请选中需要编辑的行!!','warning');
}
},
'delete':function () {
//先获取删除的数据
var row = ${domain}Datagrid.datagrid('getSelected');
//做一个判断:是否选中
if (row){
$.messager.confirm('温馨提示','你确定删除:[<font color="pink">'+row.name+"</font>]吗?",function(r){
// 选中:确认的操作:调用后台的删除方法:发送ajax调用
if (r){
// 发送ajax调用 $.get(url,params,function(d){},type)
$.get('${domain}/delete?id='+row.id,function (d) {
//d的处理
if(d.success){
//true:成功
$.messager.alert('操作提示',d.msg,'info');
//页面刷新
cmdObj.refresh();
}else{
//false:失败:提示
$.messager.alert('错误提示',d.msg,'error');
}
},'json')
}
});
}else{
$.messager.alert('温馨提示','请选中需要删除的行!!','warning');
}
},
'refresh':function () {
//datagrid的重新加载: $("selector").datagrid('funName');
${domain}Datagrid.datagrid('reload');
},
'submit':function(){
//提交:表单的提交:
${domain}Form.form('submit', {
url:'${domain}/saveOrUpdate',
onSubmit: function(){
},
success:function(data){
// {"success":true,"msg":"操作成功"}==>json字符串
var $data = $.parseJSON(data);
//弹框提示和刷新
if($data.success){
$.messager.alert('操作提示',$data.msg,'info');
}else{
$.messager.alert('错误提示',$data.msg,'error');
}
${domain}Dlg.dialog('close');
//页面刷新
cmdObj.refresh();
}
});
},
'cancel':function(){
//关闭dialog,不清空form,在打开dialog的时候清空
${domain}Dlg.dialog('close');
}
};
//toolbar绑定事件:如果按钮禁用了怎么办?下午具体实现
$("a[data-cmd]").on('click',function () {
//data-cmd="add"
var dataCmd=$(this).data('cmd');
cmdObj[dataCmd]();
});
});
domain.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<%--引入公共依赖--%>
<%@include file="/static/common/common_header.jsp"%>
<script src="/static/js/model/${domain}.js"></script>
</head>
<body>
<%--datagrid--%>
<table id="${domain}Datagrid"></table>
<%--toolbar--%>
<div id="toolbar">
<a data-cmd="add" href="javascript:void(0)" class="easyui-linkbutton c1" iconCls="icon-add" plain="true">添加</a>
<a data-cmd="edit" href="javascript:void(0)" class="easyui-linkbutton c2" iconCls="icon-edit" plain="true" >编辑</a>
<a data-cmd="delete" href="javascript:void(0)" class="easyui-linkbutton c3" iconCls="icon-remove" plain="true" >删除</a>
<a data-cmd="refresh" href="javascript:void(0)" class="easyui-linkbutton c4" iconCls="icon-reload" plain="true" >刷新</a>
</div>
<%--添加或者编辑的dialog--%>
<div id="${domain}Dlg" class="easyui-dialog" style="width: 400px"
closed="true" buttons="#dlg-buttons">
<form id="${domain}Form" method="post" novalidate style="margin:0;padding:20px 50px">
<%--编辑隐藏域的处理--%>
<input type="hidden" name="id" >
<table>
#foreach( $fieldVo in $fieldList)
<tr>
<td>
$fieldVo.title:<input type="text" name="$fieldVo.field">
</td>
</tr>
#end
</table>
</form>
</div>
<%--dialog的button--%>
<div id="dlg-buttons">
<a href="javascript:void(0)" class="easyui-linkbutton c6" iconCls="icon-ok" data-cmd="submit" style="width:90px">提交</a>
<a href="javascript:void(0)" class="easyui-linkbutton c8" iconCls="icon-cancel" data-cmd="cancel" style="width:90px">取消</a>
</div>
</body>
</html>
DomainController
package cn.web.controller;
import cn.util.AjaxResult;
import cn.util.PageResult;
import cn.domain.${Domain};
import cn.query.${Domain}Query;
import cn.service.I${Domain}Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("/${domain}")
public class ${Domain}Controller {
@Autowired
private I${Domain}Service ${domain}Service;
@RequestMapping("/index")
public String index() {
return "${domain}";
}
@RequestMapping("/list")
@ResponseBody//json
public PageResult<${Domain}> list(${Domain}Query ${domain}Query) {
return ${domain}Service.queryPage(${domain}Query);
}
// ${domain}/delete?id
@RequestMapping("/delete")
@ResponseBody//json
public AjaxResult delete(Long id) {
try {
${domain}Service.deleteByPrimaryKey(id);
return AjaxResult.success();
} catch (Exception e) {
e.printStackTrace();
return AjaxResult.error("删除失败了");
}
}
// ${domain}/saveOrUpdate
@RequestMapping("/saveOrUpdate")
@ResponseBody//json
public AjaxResult saveOrUpdate(${Domain} ${domain}) {
if (${domain} != null) {
try {
//判断是否有id,有就是修改,没有就是添加
if (${domain}.getId() != null) {
//修改
${domain}Service.updateByPrimaryKey(${domain});
} else {
//添加
${domain}Service.insert(${domain});
}
return AjaxResult.success();
} catch (Exception e) {
e.printStackTrace();
return AjaxResult.error("删除失败了");
}
}
return null;
}
}
DomainQuery
package cn.query;
import cn.query.BaseQueryObject ;
public class ${Domain}Query extends BaseQueryObject {
}
DomainServiceImpl
package cn.service.impl;
import cn.mapper.BaseMapper ;
import cn.service.impl.BaseServiceImpl ;
import cn.domain.${Domain};
import cn.mapper.${Domain}Mapper;
import cn.service.I${Domain}Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
@Service
@Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
public class ${Domain}ServiceImpl extends BaseServiceImpl<${Domain}> implements I${Domain}Service {
@Autowired
private ${Domain}Mapper ${domain}Mapper;
@Override
protected BaseMapper<${Domain}> getMapper() {
return ${domain}Mapper;
}
// 事务测试
// @Transactional
// @Override
// public void add(${Domain} ${domain}) {
// System.out.println("come on");
// ${domain}Mapper.save(${domain});
// int i=1/0;
// }
}
IDomainService
package cn.service;
import cn.service.IBaseService ;
import cn.domain.${Domain};
public interface I${Domain}Service extends IBaseService<${Domain}> {
}
运行主方法,生成对应的代码