主文件,难度不大,从头写一共花了2-3个小时吧。 主要是模板难写,不停的改不停的试,反正最后能凑合用了。 模板根据自己需要改就行了。 我这个是bootstrap+jquery的页面,后台是spring mvc的。
package freemaker;
import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.StringWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map;
import freemarker.template.Configuration; import freemarker.template.Template;
public class CreateFile {
/** * 字符串转成Filed列表 * @param str * @return */ private static List<OneField> createFieldList(String str) {
List<OneField> filedList = new ArrayList<OneField>();
String[] fArray = str.split("\\|"); for (String f : fArray) { String[] aArray = f.split(",");
OneField one = new OneField(); one.setEnglishName(aArray[0]); one.setCnName(aArray[1]); one.setType(aArray[2]); //下拉框的,取得Option的Key和value if (aArray[2].equals("select")) { String[] optionArray = aArray[3].split("#"); Map<String, String> optionMap = new LinkedHashMap<String, String>(); for (String option : optionArray) { String[] oneOption = option.split("->"); optionMap.put(oneOption[0], oneOption[1]); } one.setSelectOption(optionMap);
} //是否必填,编辑页面使用 if(aArray.length>4){ one.setRequired("required".equals(aArray[4])); } filedList.add(one); } return filedList; }
/** * 创建target目录(先删除旧的). * @return */ private static boolean deleteFolder() { // 删除目录 File targetFolder = new File("E:\\template\\create"); if (targetFolder.exists()) { //删文件 File[] fArray = targetFolder.listFiles(); for (File f : fArray) { boolean deleteFile = f.delete(); System.out.println("删除文件" + f.getName() + ":" + deleteFile); } boolean isDeleteOk = targetFolder.delete(); if (!isDeleteOk) { System.out.println("删除target目录失败"); return false; } System.out.println("删除target目录成功."); } //睡一会,要不有时报错 try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } //创建目录 boolean isCreateOK = targetFolder.mkdir(); if (!isCreateOK) { System.out.println("创建target目录失败"); return false; } System.out.println("创建target目录成功."); return true; }
public static void main(String[] args) {
//可以用页面或excel输入,我这里用字符串直接拼了~ //查询条件,查询结果,编辑页面 // String s = "sabrkey,参数,text|status,状态,select,1->启用#0->未启用"; // String s2 = "sabrkey,参数,text|sabrval,值,text|remarks,说明,text|status,状态,select,1->启用#0->未启用"; // String s3 = "sabrkey,参数,text,,required|sabrval,值,text,,required|remarks,说明,text,,|status,启用,select,1->启用#0->未启用,required"; String s = "url,网址,text|active,状态,select,1->启用#0->未启用"; String s2 = "url,网址,text|active,状态,select,1->启用#0->未启用"; String s3 = "url,网址,text,,required|active,启用,select,1->启用#0->未启用,required";
// 设置参数 Map<String, Object> map = new HashMap<String, Object>(); map.put("searchField", createFieldList(s)); map.put("resultField", createFieldList(s2)); map.put("editField", createFieldList(s3)); map.put("listFormAction", "/manage/reloadUrl/list"); map.put("saveFormAction", "/manage/reloadUrl/save"); map.put("editAction", "/manage/reloadUrl/edit"); map.put("copyAction", "/manage/reloadUrl/copy"); map.put("deleteAction", "/manage/reloadUrl/delete"); map.put("jsFileName", "reloadUrl.js"); map.put("pageTitle", "订单包参数设置"); map.put("javaBasePackage", "com.xxx"); map.put("javaBeanName", "ReloadUrl"); map.put("javaMapperName", "ReloadUrlMapper"); map.put("javaControllerName", "TableReloadUrlController");
// 配置FreeMarker Configuration cfg = new Configuration(Configuration.VERSION_2_3_23); cfg.setDefaultEncoding("UTF-8");
// 模板路径 File templateFolder = new File("E:\\template\\"); try { cfg.setDirectoryForTemplateLoading(templateFolder); } catch (IOException e) { e.printStackTrace(); }
boolean isDeleteOk = deleteFolder(); if (!isDeleteOk) { return; }
doCreateFile(cfg,"list.jsp",map,"list.jsp"); doCreateFile(cfg,"edit.jsp",map,"edit.jsp"); doCreateFile(cfg,"ipcc.js",map,map.get("jsFileName").toString()); doCreateFile(cfg,"Controller.java",map,map.get("javaControllerName").toString() + ".java");
}
/** * 根据模板替换,保存文件. * @param cfg * @param fileName 模板文件名 * @param map 变量Map * @param targetFileName 保存的文件名 */ private static void doCreateFile(Configuration cfg,String fileName,Map<String, Object> map,String targetFileName) { // 模板 Template tpl = null; try { tpl = cfg.getTemplate(fileName); } catch (Exception e) { e.printStackTrace(); }
// 执行替换 StringWriter writer = new StringWriter(); try { tpl.process(map, writer); } catch (Exception e) {
e.printStackTrace(); } String content = writer.toString();
// 写入文件 FileOutputStream fos; try { fos = new FileOutputStream(new File( "E:\\template\\create\\" + targetFileName)); OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8"); osw.write(content); osw.flush(); } catch (Exception e) { e.printStackTrace(); } }
}
OneField.java
package freemaker;
import java.util.Map;
public class OneField {
private String englishName; private String cnName; /** * 类型:text,select */ private String type; private Map<String,String> selectOption; /** * 是否必须输入. */ private boolean required;
public String getEnglishName() { return englishName; }
public void setEnglishName(String englishName) { this.englishName = englishName; }
public String getCnName() { return cnName; }
public void setCnName(String cnName) { this.cnName = cnName; }
public String getType() { return type; }
public void setType(String type) { this.type = type; }
public Map<String, String> getSelectOption() { return selectOption; }
public void setSelectOption(Map<String, String> selectOption) { this.selectOption = selectOption; }
public boolean isRequired() { return required; }
public void setRequired(boolean required) { this.required = required; }
}
----------------------------------- 模板文件: list.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ include file="../../include/top.jsp"%>
<script src="${"$"}{ctx}/static/js/${jsFileName}"></script>
<div class="container" style="width: 100%"> <div class="row clearfix"> <div class="col-md-12 column"> <h1 class="text-center">${pageTitle}</h1> <!-- ===========================表单区域================================= --> <form class="form-inline" action="${"$"}{ctx}${listFormAction}" method="post" name="searchForm" id="searchForm" style="line-height: 300%">
<#list searchField as field > <#if field.type=="text"> <div class="form-group"> <label for="${field.englishName}">${field.cnName}:</label><input type="text" id="${field.englishName}" name="${field.englishName}" class="form-control" value="${"$"}{param.${field.englishName}}"/> </div></#if> <#if field.type=="select"> <div class="form-group"> <label for="${field.englishName}">${field.cnName}:</label><select id="${field.englishName}" name="${field.englishName}" class="form-control" > <option value="">--请选择--</option> <#list field.selectOption?keys as key> <option value="${key}">${field.selectOption[key]}</option> </#list> </select> </div> <script>${"$"}("#${field.englishName}").val("${"$"}{param.${field.englishName}}")</script> </#if> </#list>
<input type="submit" name="search" class="btn btn-primary" value="查询" /> <input type="button" name="clear" class="btn" value="清空" onclick="clearInput()"/> </form> <hr /> <input type="button" name="add" class="btn btn-info" value="添加" onclick="addRow()"/><br/><br/> <!-- ===========================结果区域================================= --> <c:if test="${"$"}{empty pager.list}"> 没有符合条件的记录。 </c:if> <c:if test="${"$"}{not empty pager.list }"> <table class="table table-striped table-bordered" style="word-break:break-all;min-width:800px"> <thead> <tr> <th width="5%"></th> <#list resultField as field > <th width="10%">${field.cnName}</th> </#list> <th>操作</th> </tr> </thead> <tbody> <c:forEach items="${"$"}{pager.list}" var="info" varStatus="status"> <tr> <td>${"$"}{status.count}</td> <#list resultField as field > <#if field.type=="text"> <td>${"$"}{info.${field.englishName}}</td> </#if> <#if field.type=="select"> <td> <#list field.selectOption?keys as key> <c:if test="${"$"}{info.${field.englishName}=='${key}'}">${field.selectOption[key]}</c:if> </#list> </td> </#if> </#list> <td> <input type="button" value="复制" onclick="copyRow(${"$"}{info.id})"/> <input type="button" value="修改" onclick="editRow(${"$"}{info.id})"/> <input type="button" value="删除" onclick="deleteRow(${"$"}{info.id})"/> </td> </tr> </c:forEach> <tr> <td colspan="20" align="left"><pg:pager items="${"$"}{pager.total}" url="${"$"}{ctx}${listFormAction}" maxPageItems="${"$"}{pager.pageSize }" maxIndexPages="5" export="currentPageNumber=pageNumber"> <pg:param name="pageSize" value="10" /> <#list searchField as field > <pg:param name="${field.englishName}" value="${"$"}{param.${field.englishName}}" /> </#list>
共${"$"}{pager.total}条 <pg:first> <a href="${"$"}{pageUrl}&p=1">首页</a> </pg:first> <pg:prev> <a href="${"$"}{pageUrl}&p=${"$"}{currentPageNumber-1}">上一页</a> </pg:prev> <pg:pages> <c:choose> <c:when test="${"$"}{currentPageNumber eq pageNumber}"> <font color="red">${"$"}{pageNumber}</font> </c:when> <c:otherwise> <a href="${"$"}{pageUrl}&p=${"$"}{pageNumber}">${"$"}{pageNumber}</a> </c:otherwise> </c:choose> </pg:pages> <pg:next> <a href="${"$"}{pageUrl}&p=${"$"}{currentPageNumber+1}">下一页</a> </pg:next> <pg:last> <a href="${"$"}{pageUrl}&p=${"$"}{pageNumber}">尾页</a> </pg:last> </pg:pager></td> </tr> </tbody> </table> </c:if> </div> </div> </div> </body> </html>
edit.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ include file="../../include/top.jsp"%> <script src="${"$"}{ctx}/static/js/${jsFileName}"></script>
<div class="container" style="width: 100%"> <div class="row clearfix"> <div class="col-md-12 column"> <h1 class="text-center"><c:if test="${"$"}{not empty row.id}">编辑</c:if><c:if test="${"$"}{empty row.id}">新增</c:if></h1> <form role="form" class="form-inline" id="editForm" > <input type="hidden" id="id" name="id" class="form-control" value="${"$"}{row.id}"/> <#list editField as field > <#if field.type=="text"> <div class="form-group"> <label for="${field.englishName}">${field.cnName}:</label><input type="text" id="${field.englishName}" name="${field.englishName}" class="form-control" value="${"$"}{row.${field.englishName}}"/> </div><br/></#if> <#if field.type=="select"> <div class="form-group"> <label for="${field.englishName}">${field.cnName}:</label><select id="${field.englishName}" name="${field.englishName}" class="form-control" > <option value="">--请选择--</option> <#list field.selectOption?keys as key> <option value="${key}">${field.selectOption[key]}</option> </#list> </select> </div><br/> <script>${"$"}("#${field.englishName}").val("${"$"}{row.${field.englishName}}")</script> </#if> </#list> <div class="text-center"> <input type="submit" name="save" class="btn btn-primary" value="保存"/> <input type="button" name="close" class="btn" value="关闭" onclick="closeWin()"/> </div> </form> <script>
//输入check,默认隐藏的元素不check ${"$"}("#editForm").validate({ rules : { <#list editField as field > <#if field.required> ${field.englishName} : "required", </#if> </#list> }, submitHandler : function(form) { //提交 var url = ctx + '${saveFormAction}'; ${"$"}.ajax({ type : "POST", url : url, data : ${"$"}("#editForm").serializeJSON(), dataType : "json", success : function(data) { if (data.result == "OK") { alert("保存成功."); closeWin(); } else { alert(data.message); } }, }); } }); </script> </div> </div> </div> </body> </html>
ipcc.js
function reloadData(){ window.location.reload(true); }
// 清空表单输入 function clearInput() { <#list searchField as field > ${"$"}("#${field.englishName}").val(""); </#list> }
// 编辑 function editRow(id) { var url = ctx + '${editAction}?id=' + id; openWin("编辑", url, 1000, 500, function() { reloadData(); }); }
// 增加 function addRow() { var url = ctx + '${editAction}'; openWin("编辑", url, 1000, 500, function() { reloadData(); }); }
//复制 function copyRow(id) { var url = ctx + '${copyAction}?id=' + id; openWin("编辑", url, 1000, 500, function() { reloadData(); }); }
// 删除 function deleteRow(id) { if (!confirm("确认删除?")) { return; }
var url = ctx + '${deleteAction}?id=' + id; $.ajax({ type : "POST", url : url, dataType : "json", success : function(data) { if (data.result == "OK") { alert("删除成功."); reloadData(); } else { alert(data.message); } }, }); }
Controller.java
package ${javaBasePackage}.action;
import java.util.HashMap; import java.util.List; import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang.StringUtils; 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;
import tk.mybatis.mapper.entity.Example; import tk.mybatis.mapper.entity.Example.Criteria;
import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import ${javaBasePackage}.domain.${javaBeanName}; import ${javaBasePackage}.persistence.${javaMapperName};
/** * IPCC管理. * */ @Controller public class ${javaControllerName} {
/** * 管理Mapper. */ @Autowired private ${javaMapperName} ${javaMapperName?uncap_first};
/** * 查询数据. * * @param params * @param response * @return */ @RequestMapping(value = "${listFormAction}") public String query(${javaBeanName} params,Integer p , Integer pageSize,HttpServletRequest request) {
// 分页查询 if (p == null || p.intValue() <= 0) { p = 1; } if (pageSize == null || pageSize.intValue() <= 0 || pageSize.intValue() > 100) { pageSize = 10; } PageHelper.startPage(p, pageSize); // 当前页数,每页多少条 // 查询条件,模糊查询 Example example = new Example(${javaBeanName}.class); Criteria cri = example.createCriteria(); <#list searchField as field > if (!StringUtils.isEmpty(params.get${field.englishName?cap_first}())) { cri.andEqualTo("${field.englishName}", params.get${field.englishName?cap_first}()); } </#list> //example.setOrderByClause("ipcc asc"); // 排序
// 查询 List<${javaBeanName}> list = ${javaMapperName?uncap_first} .selectByExample(example);
// 分页 PageInfo<${javaBeanName}> pager = new PageInfo<${javaBeanName}>(list); // 返回 request.setAttribute("pager", pager); request.setAttribute("param", params); return "${listFormAction}"; }
/** * 编辑页面. * * @param request * @return */ @RequestMapping(value = "${editAction}") public String edit(Integer id, HttpServletRequest request) { ${javaBeanName} row = null; if (id == null) { row = new ${javaBeanName}(); } else { row = ${javaMapperName?uncap_first}.selectByPrimaryKey(id); } request.setAttribute("row", row);
return "${editAction}"; }
/** * 复制数据,到编辑页面. * * @param request * @return */ @RequestMapping(value = "${copyAction}") public String copyExpression(Integer id, HttpServletRequest request) { ${javaBeanName} row = null; if (id == null) { row = new ${javaBeanName}(); } else { row = ${javaMapperName?uncap_first}.selectByPrimaryKey(id); row.setId(null); // id置空 } request.setAttribute("row", row);
return "${editAction}"; }
/** * 保存数据. * * @param request * @return */ @RequestMapping(value = "${saveFormAction}") @ResponseBody public Map<String, String> saveData(${javaBeanName} row, HttpServletRequest request) {
// 插入或更新 int count = 0; if (row.getId() == null) {
// 插入 count = ${javaMapperName?uncap_first}.insertSelective(row); } else {
// 更新 count = ${javaMapperName?uncap_first}.updateByPrimaryKeySelective(row); }
// 返回 if (count == 1) { return this.createOKMsg("保存成功。"); } else { return this.createNGMsg("保存失败。"); } }
/** * 删除数据. * * @param request * @return */ @RequestMapping(value = "${deleteAction}") @ResponseBody public Map<String, String> deleteData(Integer id, HttpServletRequest request) {
// 插入或更新 int count = 0; if (id != null) { count = ${javaMapperName?uncap_first}.deleteByPrimaryKey(id); }
// 返回 if (count == 1) { return this.createOKMsg("删除成功。"); } else { return this.createNGMsg("删除失败。"); } } /** * 创建NG的消息. * * @param msg * 消息文字. * @return */ public Map<String, String> createNGMsg(String msg) { Map<String, String> m = new HashMap<String, String>(); m.put("result", "NG"); m.put("message", msg); return m; }
/** * 创建OK的消息. * * @param msg * 消息文字. * @return */ public Map<String, String> createOKMsg(String msg) { Map<String, String> m = new HashMap<String, String>(); m.put("result", "OK"); m.put("message", msg); return m; } }
-------------------------------------------------- include/top.jsp,供参考吧。
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@page import="java.util.*"%> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%> <%@taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%> <%@taglib prefix="pg" uri="http://jsptags.com/tags/navigation/pager"%>
<c:set var="ctx" value="${pageContext.request.contextPath}" /> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="x-ua-compatible" content="IE=9"> <meta name="renderer" content="webkit"> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>xxx系统</title> <link href="${ctx}/static/css/bootstrap.min.css" rel="stylesheet"> <script src="${ctx}/static/js/jquery-1.9.1.min.js"></script> <script src="${ctx}/static/js/My97DatePicker/WdatePicker.js"></script>
<!-- 验证框架--> <script src="${ctx}/static/js/jquery/jquery.validate.min.js"></script> <script src="${ctx}/static/js/jquery/additional-methods.min.js"></script> <script src="${ctx}/static/js/jquery/localization/messages_zh.min.js"></script>
<!-- 弹窗框架--> <script src="${ctx}/static/js/layer/layer.js"></script> <script src="${ctx}/static/js/bootstrap.min.js"></script> <script src="${ctx}/static/js/jquery/jquery.layout-latest.js"></script>
<script src="${ctx}/static/js/common.js"></script> <script src="${ctx}/static/js/jquery.serializejson.js"></script> <script> var ctx="${ctx}"; </script> <style>
label.error { color: red; font-weight: normal; margin-left: 0.5em; float: none; }
select.error,input.error { border: 1px dotted red; } </style> </head> <body>
分页插件和jspTag,在Maven的POM里加这个:
<!-- 分页查询组件 --> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>4.0.0</version> </dependency> <dependency> <groupId>jsptags</groupId> <artifactId>pager-taglib</artifactId> <version>2.0</version> </dependency>
common.js,主要是layer弹窗的封装方法。
//字符串以xx结尾 String.prototype.endWith=function(endStr){ var d=this.length-endStr.length; return (d>=0&&this.lastIndexOf(endStr)==d); };
//父窗口调用此方法 function openWin(winTitle,winURL,width,height,callback){ var winWidth = width==null?"90%":""+width; var winHeight = height==null?"90%":""+height; if(!winWidth.endWith("%"))winWidth+="px"; if(!winHeight.endWith("%"))winHeight+="px"; top.layer.open({ type: 2, maxmin: false, title: winTitle, shade: [0.5,'#333'], offset: ['50px', ''], //上边距50像素 area: [winWidth, winHeight], content:winURL }); //保存callback,根据子窗口的index来索引 if(callback && typeof(callback) === "function"){ share.data(top.layer.index,callback); } } //此方法由子窗口调用,故window.name是iframe页面的name function closeWin(data){ //取得callback var callback = share.remove(top.layer.getFrameIndex(window.name)); if(callback && typeof(callback) === "function"){ //callback初始是由父窗口创建的,所以此时回调时,仍然是父窗口执行的。 callback(data); } //关闭窗口 top.layer.close(top.layer.getFrameIndex(window.name)); /* if (data) { var aaa = parent.$('.tabs-inner span'); for (var i = 0; i < aaa.length; i++) { var t =aaa[i].textContent; i++; if (t.indexOf("补")!=-1) { parent.$('#tabs').tabs('close',t); } } }*/ } var share = {
/** * 跨框架数据共享接口 * @param {String} 存储的数据名 * @param {Any} 将要存储的任意数据(无此项则返回被查询的数据) */ data: function (name, value) { var top = window.top, cache = top['_CACHE'] || {}; top['_CACHE'] = cache; return value !== undefined ? cache[name] = value : cache[name]; }, /** * 数据共享删除接口 * @param {String} 删除的数据名 */ remove: function (name) { var cache = window.top['_CACHE']; var value = null; if (cache && cache[name]){ value = cache[name]; delete cache[name]; } return value; } };
|