【公司动态添加行】前台穿一个json的字符串到后台,并解析

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="Generator" content="EditPlus®">
<meta name="Author" content="">
<meta name="Keywords" content="">
<meta name="Description" content="">
<title>代码自动转换</title>
<link href="css/bootstrap.min.css" rel="stylesheet" type="text/css"/>
<link href="css/base.css" rel="stylesheet" type="text/css"/>
<link href="css/fistIndex.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div id="header_s">
<ol>
<li><img src="">图片自己定义</li>
<li class="back"><a href="daima.html" >通过类自动生成代码</a></li>
<li class="back"><a href="daima2.html">通过SQL自动生成代码</a></li>
<li class="back"><a href="daima3.html">使用说明</a></li>
</ol>

</div>
<div id="content_s" class="clear">
<h4>表单输入和验证</h4>
<form>
<div id="div_monad">
<tr>
<td>java类包路径</td>
<td><input placeholder="请输入java类包路径" type="text" id="packeDir"/><span id="error1"></span> </td>
<td> <input placeholder="请输入类名" type="text" id="className"/><span id="error2"></span> </td>

</tr><br>
<tr class="clear">
<td><input type="button" value="添加" id="btn_addUpload"></td>
<td><input type="button" value="生成代码" id="btn_creatCode"></td>
<td><input type="button" value="保存" id="btn_save"></td>
</tr><br>
<tr id="table_s">
<th>权限</th>
<th>类型</th>
<th>属性名</th>
<th>主键</th>
<th>备注</th>
</tr>
<div id="div_tab_first" ></div>
</div>
<table id='tbody' align="center">

</table>
</form>
</div>
<script src="js/jquery-2.1.4.min.js" type="text/javascript"></script>
<script >
$(".back").mousemove(function(){
$(this).attr("style","background-color:#432;");
});
$(".back").mouseout(function(){
$(this).attr("style","");
});

var rLicNoKey = 'id';
/* var uploadControlString = '<tr class="even">'
+ '<td align="center"><input id="spCodeFile_{index}" type="text" validators="validators:required,maxLength=10,pattern=regex[数据格式不正确]" regex="^((-)?d*(.)?d*)$" maxlength="10" name="{spCode}"></input>'
+ '<td align="center"><input id="spNameFile_{index}" type="text" style=" 95%;" maxlength="60" name="{spName}"></input></td>'
+ '</tr>'; */
var uploadControlString = '<tr><td><select name="spLimit" id="spLimit_{index}"><option value="private">private</option><option value="public">public</option></select></td>'
+'<td><select name="spNature" id="spNature_{index}"><option value="String">String</option><option value="int">int</option><option value="char">char</option><option value="byte">byte</option><option value="shot">shot</option><option value="long">long</option><option value="float">float</option><option value="double">double</option><option value="boolean">boolean</option></select></td>+'
+'<td><input type="text" id="spAttName_{index}"></td>'
+'<td><input id="sppriKey_{index}" type="checkbox"/></td>'
+'<td><input type="text" id="spRemark_{index}"></td>'
+'<td><a href="#" id="remove_{index}">删除</a></td>'
+'</tr>';

var uploadGlobalArray = new Array();
var uploadGlobalMap = {};
var rowSelects = {};
var uploadTab = $('#div_tab_first');
var indexGlobal = 0;
var countGlobal = 0;

addUpload();

function addUpload() {
indexGlobal = indexGlobal + 1;
var t = $(this);
var u = '' + uploadControlString;
var index = indexGlobal;
//--修改新增控件的名称、ID和题头
u = u.replace('{index}', index).replace('{index}', index).replace('{index}', index).replace('{index}', index).replace('{index}', index).replace('{index}', index);
/* u = u.replace('{spName}', index);

u = u.replace('{spCode}', index); */
var $upload = $(u);

// uploadGlobalArray.push($upload);
uploadGlobalMap[index] = $upload;
uploadTab.append($upload);
var ctlUploadNewId = "select_" + index;
$("#" + ctlUploadNewId).html($("#listSample").html());
rowSelects[index] = index;
var id_remove = "#remove_" + index;
// alert(id_remove);
$(id_remove).bind('click', {
'index': index
}, function (e) {
removeOne(e);
});
countGlobal = countGlobal + 1;
}
function removeUpload() {
if (countGlobal > 0) {
var t = $(this);
// var temp = uploadGlobalArray.pop();
var temp = uploadGlobalMap[indexGlobal];
delete uploadGlobalMap[indexGlobal];
delete rowSelects[indexGlobal];
temp.remove();
countGlobal = countGlobal - 1;
}
}
function removeOne(that) {
var index = that.data.index;
var temp = uploadGlobalMap[index];
// uploadGlobalArray.pop();
delete uploadGlobalMap[index];
delete rowSelects[index];
temp.remove();
countGlobal = countGlobal - 1;
return false;
}
function save() {
/* if (countGlobal <= 0) {
alert("数据输入不完整");
return false;
} else { */
var jsonItemsString = "";
for ( var i in rowSelects) {
var spLimit = $("#spLimit_" + rowSelects[i]).val();
var spNature = $("#spNature_" + i).val(); //
var spAttName = $("#spAttName_" + i).val(); //
var sppriKey = $("#sppriKey_" + i).val(); //
var spRemark = $("#spRemark_" + i).val(); //

if (spNature == "") {
alert("属性名不能为空");
return false;
}
if (spNature != "") { //-- HS编号与品名都未录入的行忽略掉,只保存都录入的行
var tempString = '{"spLimit":"' + spLimit
+ '","spNature":"' + spNature + '","spAttName":"' + spAttName
+ '","sppriKey":"' + sppriKey + '","spRemark":"' + spRemark+'"}';
if (jsonItemsString.length > 0){
jsonItemsString = jsonItemsString + "," + tempString;
} else {
jsonItemsString = tempString;
}
}
}
var packeDir=$("#packeDir").val();
var className=$("#className").val();
var nameTotle='{"classDir":"'+packeDir+'","className":"'+className+'"}';
if (jsonItemsString.length > 0) { //--判断是否有需要保存的数据
jsonItemsString = "[" + jsonItemsString + "]";
nameTotle = "[" + nameTotle + "]";
//ajax 请求
$.post('insert', {
'nameTotle':nameTotle,
'jsonItemsString' : jsonItemsString
}, function(data) {
change();
alert(data);
});
} else {
return false;
}

}

$('#btn_addUpload').bind('click', addUpload);
$('#removeUpload').bind('click', removeUpload);
$('#btn_save').bind('click', save);
</script>
</body>
</html>

package com.feiyx.autojcode;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.feiyx.bean.BigEntity;
import com.feiyx.bean.ClassName;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateException;


/**
* @author 【狒狒Q:9715234】
* @time 2016-1-27 下午5:41:45
*
* @motto 既然笨到家,就要努力到家...
*
*/
public class FeiTotalManager extends HttpServlet {
private static final long serialVersionUID = 1L;

public void service(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
response.setContentType("text/html;charset=utf-8");

String className = request.getParameter("nameTotle");
List<ClassName> classNameList = JsonUtil.getJavaCollection(
new ClassName(), className);
// ClassName classNam=(ClassName)classNameList.get(0);
System.out.println(className.toString());

String jsonItemsString = request.getParameter("jsonItemsString");
List<BigEntity> bigEntityList = JsonUtil.getJavaCollection(
new BigEntity(), jsonItemsString);
System.out.println(jsonItemsString);

try {
FeiTotalManager.beanTool(bigEntityList,classNameList);
} catch (Exception e) {
e.printStackTrace();
}
int i = 0;
if (i == 1) {
out.print("O(∩_∩)O 提交成功!"+i);
} else {
out.print("o(︶︿︶)o 唉!失败了!");
}
}
/**
*
* @param classes
* @param entryPath
* @param tarPath
* @param templateName
* @throws Exception
*/
public static void createBeanService(List<BigEntity> bigEntity,List<ClassName> className,String templateName) throws Exception{
String cName=className.get(0).getClassName();
String classDir=className.get(0).getClassDir();

/** SRC的目录 **/
String PathSrc=Constants.PATH_PROJECT_SRC;
/**模板的目录**/
String templatePath=Constants.PATH_PROJECT_TEMP;

/** 导出的目标路径 **/

File tarfile=new File(PathSrc,cName+"Service.java");
FileWriter fw = new FileWriter(tarfile); //导出的目录

File file = new File(templatePath); //模板文件路径
// String templateName=cName+"service.java";
String templateEncoding="UTF-8";

Map<String, List> map = new HashMap<String, List>();

map.put("classList", bigEntity);
map.put("className", className);
createJava(file,templateName, templateEncoding, map , fw);
}
/**
*
* @param file
* @param templateName
* @param templateEncoding
* @param root
* @param fw
*/

public static void createJava(File file, String templateName,String templateEncoding,Map<?,?> root ,FileWriter fw) {
try {
Configuration config=new Configuration();

//设置要解析的模板所在的目录,并加载模板文件
config.setDirectoryForTemplateLoading(file);
//设置包装器,并将对象包装为数据模型
config.setObjectWrapper(new DefaultObjectWrapper());
config.setDefaultEncoding(templateEncoding);
//获取模板,并设置编码方式,这个编码必须要与页面中的编码格式一致
Template template=config.getTemplate(templateName,templateEncoding);
template.setEncoding(templateEncoding);

template.process(root, fw);
fw.flush();
fw.close();
} catch (IOException e) {
e.printStackTrace();
}catch (TemplateException e) {
e.printStackTrace();
}

}
/**
*
* @param c
* @param EntryPath
* @param tarPath
* @throws Exception
*/
public static void beanTool(List<BigEntity> list,List<ClassName> className)throws Exception{
createBeanService(list,className,"temp_inface.ftl");
}

}

commons-beanutils-1.7.0.jar
commons-collections-3.1.jar
commons-httpclient-3.0.jar
commons-lang-2.3.jar
commons-logging-1.0.4.jar
ezmorph-1.0.4.jar
freemarker.jar
hibernate-annotations.jar
json-lib-2.4-jdk15.jar
mysql-connector-java-5.1.30-bin.jar
rapid-generator-4.0.jar
servlet-api.jar

需要这些jar包

/**得到javaCoolection
* List<SafePlan> javaCollection = JsonUtil.getJavaCollection(new SafePlan(), s);
* @param clazz
* @param jsons
* @return
*/
public static <T> List<T> getJavaCollection(T clazz, String jsons) {
if(StringUtils.isBlank(jsons))
return null;
List<T> objs = null;
JSONArray jsonArray = (JSONArray) JSONSerializer.toJSON(jsons);
if (jsonArray != null) {
objs = new ArrayList<T>();
List list = (List) JSONSerializer.toJava(jsonArray);
for (Object o : list) {
JSONObject jsonObject = JSONObject.fromObject(o);
T obj = (T) JSONObject.toBean(jsonObject, clazz.getClass());
objs.add(obj);
}
}
return objs;
}

/**
* 转换LIST为 jsonStr
* @param list
* @return
*/
public static String getJavaCollectionJsonStr(List list){
JSONArray jsonArray3 = JSONArray.fromObject( list );
return jsonArray3.toString();
}

public static String getJavaObjectJsonStr(Object list){
JSONObject fromObject = JSONObject.fromObject(list );
return fromObject.toString();
}

原文地址:https://www.cnblogs.com/feiyuanxing/p/5175895.html