rpc接口mock平台
转载:http://blog.csdn.net/ronghuanye/article/details/71124320
1、简介
平台采用struts、spring、mybatis框架开发设计,主要用来管理mock接口数据,也可以用来管理接口自动化,并集成一些常用工具。
2、架构设计
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<!-- web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
-->
<web-app version="2.4"
xmlns=" http://java.sun.com/xml/ns/j2ee"
xmlns:xsi=" http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation=" http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<welcome-file-list>
<welcome-file>login.jsp</welcome-file>
</welcome-file-list>
<context-param>
<param-name>webAppRootKey</param-name>
<param-value>webApp.SM1</param-value>
</context-param>
<!-- 与Spring整合-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<dependency>
<artifactId>slf4j-log4j12</artifactId>
<version>1.5.8</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.13</version>
</dependency>
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>classpath:log4j.properties</param-value>
</context-param>
<!-- 每隔60秒检测一下Lo4j配置文件 -->
<context-param>
<param-name>log4jRefreshInterval</param-name>
<param-value>60000</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
<!-- 定义Struts2的FilterDispathcer过滤器的Filter -->
<filter>
<filter-name>Struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
</filter>
<!-- FilterDispatcher用来初始化struts2并且处理所有的WEB请求。 -->
<filter-mapping>
<filter-name>Struts2</filter-name>
<url-pattern>*.jsp</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>Struts2</filter-name>
<url-pattern>*.action</url-pattern>
</filter-mapping>
</web-app>
view层
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import com.huawei.vmall.test.service.MockService;
import com.huawei.vmall.test.util.BaseAction;
import com.huawei.vmall.test.util.Utils;
import net.sf.json.JSONObject;
public class MockAction extends BaseAction{
private static final long serialVersionUID = 1L;
private Logger logger = Logger.getLogger(MockAction.class);
@Autowired
private MockService mockService;
private int id;
private int status;
private String interfaceName;
private String methodName;
private String paramTypes;
private String paramJson;
private String returnType;
private String returnJson;
private int page;
private int rows;
//web query mock
public void getMock() {
String res = "";
try
{
Map<String, Object> map = new HashMap<String, Object>();
map.put("page", this.getPage());
map.put("rows", this.getRows());
res = mockService.getMock(map);
this.sendMsg(res);
}
catch(Exception e)
{
logger.error(e);
this.sendMsg("{\"success\":false,\"errorMsg\":\"" + e.toString() + "\"}");
}
}
//filter query mock
public void goMock() {
List<Map<String,Object>> res = null;
try
{
//json对象
JSONObject jsonObj = JSONObject.fromObject(Utils.getPostContent(this.getRequest()));
Map<String, Object> map = new HashMap<String, Object>();
map.put("interfaceName", jsonObj.getString("interfaceName"));
map.put("methodName",jsonObj.getString("methodName"));
map.put("paramTypes", jsonObj.getString("paramTypes"));
map.put("paramJson", jsonObj.getString("paramJson"));
map.put("returnType", jsonObj.getString("returnType"));
res = mockService.goMock(map);
if(res.size()>0)
{
this.sendMsg("{\"success\":true,\"message\":"+JSONObject.fromObject(res.get(0)).toString()+"}");
} else {
this.sendMsg("{\"success\":true,\"message\":\"\"}");
}
}
catch(Exception e)
{
logger.error(e);
this.sendMsg("{\"success\":false,\"errorMsg\":\"" + e.toString() + "\"}");
}
}
//filter add mock
public void addMock() {
try
{
//json对象
JSONObject jsonObj = JSONObject.fromObject(Utils.getPostContent(this.getRequest()));
Map<String, Object> map = new HashMap<String, Object>();
map.put("interfaceName", jsonObj.getString("interfaceName"));
map.put("methodName",jsonObj.getString("methodName"));
map.put("paramTypes", jsonObj.getString("paramTypes"));
map.put("paramJson", jsonObj.getString("paramJson"));
map.put("returnType", jsonObj.getString("returnType"));
map.put("returnJson", jsonObj.getString("returnJson"));
map.put("status", 0);
mockService.addMock(map);
this.sendMsg("{\"success\":true,\"message\":\"执行成功\"}");
}
catch(Exception e)
{
logger.error(e);
this.sendMsg("{\"success\":false,\"errorMsg\":\"" + e.toString() + "\"}");
}
}
//web add Mock
public void newMock() {
try
{
Map<String, Object> map = new HashMap<String, Object>();
map.put("interfaceName", this.getInterfaceName());
map.put("methodName",this.getMethodName());
map.put("paramTypes", this.getParamTypes());
map.put("paramJson", this.getParamJson());
map.put("returnType", this.getReturnType());
map.put("returnJson", this.getReturnJson());
map.put("status", this.getStatus());
mockService.addMock(map);
this.sendMsg("{\"success\":true,\"message\":\"执行成功\"}");
}
catch(Exception e)
{
logger.error(e);
this.sendMsg("{\"success\":false,\"errorMsg\":\"" + e.toString() + "\"}");
}
}
//update mock
public void updateMock() {
try
{
Map<String, Object> map = new HashMap<String, Object>();
map.put("interfaceName", this.getInterfaceName());
map.put("methodName",this.getMethodName());
map.put("paramTypes", this.getParamTypes());
map.put("paramJson", this.getParamJson());
map.put("returnType", this.getReturnType());
map.put("returnJson", this.getReturnJson());
map.put("status", this.getStatus());
map.put("id", this.getId());
mockService.updateMock(map);
this.sendMsg("{\"success\":true,\"message\":\"执行成功\"}");
}
catch(Exception e)
{
logger.error(e);
this.sendMsg("{\"success\":false,\"errorMsg\":\"" + e.toString() + "\"}");
}
}
//delete Mock
public void deleteMock() {
try
{
Map<String, Object> map = new HashMap<String, Object>();
map.put("id", this.getId());
mockService.deleteMock(map);
this.sendMsg("{\"success\":true,\"message\":\"执行成功\"}");
}
catch(Exception e)
{
logger.error(e);
this.sendMsg("{\"success\":false,\"errorMsg\":\"" + e.toString() + "\"}");
}
}
public int getId()
{
return id;
}
public void setId(int id)
{
this.id = id;
}
public int getStatus()
{
return status;
}
public void setStatus(int status)
{
this.status = status;
}
public String getInterfaceName()
{
return interfaceName;
}
public void setInterfaceName(String interfaceName)
{
this.interfaceName = interfaceName;
}
public String getMethodName()
{
return methodName;
}
public void setMethodName(String methodName)
{
this.methodName = methodName;
}
public String getParamTypes()
{
return paramTypes;
}
public void setParamTypes(String paramTypes)
{
this.paramTypes = paramTypes;
}
public String getParamJson()
{
return paramJson;
}
public void setParamJson(String paramJson)
{
this.paramJson = paramJson;
}
public String getReturnType()
{
return returnType;
}
public void setReturnType(String returnType)
{
this.returnType = returnType;
}
public String getReturnJson()
{
return returnJson;
}
public void setReturnJson(String returnJson)
{
this.returnJson = returnJson;
}
public int getPage()
{
return page;
}
public void setPage(int page)
{
this.page = page;
}
public int getRows()
{
return rows;
}
public void setRows(int rows)
{
this.rows = rows;
}
}
service层
import java.util.List;
import java.util.Map;
import com.huawei.vmall.test.util.PaginationResultImpl;
import com.huawei.vmall.test.util.TmasException;
public interface MockService {
String getMock(Map<String, Object> map) throws TmasException;
List<Map<String,Object>> goMock(Map<String, Object> map) throws TmasException;
void addMock(Map<String, Object> map) throws TmasException;
void updateMock(Map<String, Object> map);
void deleteMock(Map<String, Object> map);
}
import java.util.List;
import java.util.Map;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.huawei.vmall.test.mapper.MockMapper;
import com.huawei.vmall.test.util.PaginationResultImpl;
import com.huawei.vmall.test.util.TmasException;
import net.sf.json.JSONArray;
@Service("MockService")
public class MockServiceImpl implements MockService {
@Autowired
private MockMapper mockMapper;
public String getMock(Map<String, Object> map) throws TmasException
{
// 总行数
int rowTotal = mockMapper.queryMockCount();
int page = Integer.parseInt(map.get("page").toString());
int rows = Integer.parseInt(map.get("rows").toString());
map.put("offset", (page-1)*rows);
List<Map<String, Object>> list = mockMapper.getMock(map);
return "{\"total\":\""+rowTotal+"\",\"rows\":"+JSONArray.fromObject(list).toString()+"}";
}
@Override
public List<Map<String, Object>> goMock(Map<String, Object> map) throws TmasException
{
return mockMapper.goMock(map);
}
@Override
public void addMock(Map<String, Object> map) throws TmasException
{
mockMapper.addMock(map);
}
@Override
public void updateMock(Map<String, Object> map)
{
mockMapper.updateMock(map);
}
@Override
public void deleteMock(Map<String, Object> map)
{
mockMapper.deleteMock(map);
}
}
dao层
import java.util.List;
import java.util.Map;
import org.apache.ibatis.session.RowBounds;
public interface MockMapper {
List<Map<String, Object>> getMock(Map<String, Object> map);
List<Map<String, Object>> goMock(Map<String, Object> map);
void addMock(Map<String, Object> map);
void updateMock(Map<String, Object> map);
void deleteMock(Map<String, Object> map);
int queryMockCount();
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.huawei.vmall.test.mapper.MockMapper">
<select id="queryMockCount" resultType="int">
SELECT count(*) from mock
</select>
<select id="getMock" resultType="Map">
SELECT * from mock order by id LIMIT #{offset},#{rows};
</select>
<select id="goMock" parameterType="Map" resultType="Map">
SELECT status,returnJson from mock where
interfaceName=#{interfaceName} and
methodName=#{methodName} and
paramTypes=#{paramTypes}
</select>
<select id="addMock" parameterType="Map" >
insert into mock(interfaceName,
methodName,
paramTypes,
paramJson,
returnType,
returnJson,
keyword,
status)
VALUES(#{interfaceName},
#{methodName},
#{paramTypes},
#{paramJson},
#{returnType},
#{returnJson},
'',
#{status})
</select>
<select id="updateMock" parameterType="Map">
update mock set
interfaceName=#{interfaceName},
methodName=#{methodName},
paramTypes=#{paramTypes},
paramJson=#{paramJson},
returnType=#{returnType},
status=#{status}
where id = #{id}
</select>
<select id="deleteMock" parameterType="Map">
DELETE FROM mock where id = #{id}
</select>
</mapper>
util类:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.util.Properties;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
import com.mysql.jdbc.Statement;
@SuppressWarnings("deprecation")
public class Utils {
public static String getConfig(File file,String key){
String value = "";
try {
FileInputStream fis = new FileInputStream(file);
Properties prop = new Properties();
prop.load(fis);
value = prop.getProperty(key);
} catch (Exception e) {
e.printStackTrace();
}
return value;
}
public static Connection getConn(File file){
Connection connection = null;
//File file;
String url;
String username;
String passwd;
try {
//file = new File("config/yslow.config");
url = Utils.getConfig(file, "mysql_url");
username = Utils.getConfig(file, "mysql_username");
passwd = Utils.getConfig(file, "mysql_passwd");
Class.forName("com.mysql.jdbc.Driver");
connection = (Connection)DriverManager.getConnection(url, username, passwd);
} catch (Exception e) {
e.printStackTrace();
}
return connection;
}
public static ResultSet execSQL(String sql, File file){
ResultSet rs = null;
Statement stat = null;
try {
stat = (Statement) Utils.getConn(file).createStatement();
rs = stat.executeQuery(sql);
} catch (Exception e) {
System.out.println("数据库参数配置错误,请检查。。。");
e.printStackTrace();
}
return rs;
}
public static ResultSet execSQL(String sql,String param,File file){
PreparedStatement pStatement = null;
ResultSet rs = null;
try {
pStatement = (PreparedStatement) Utils.getConn(file).prepareStatement(sql);
pStatement.execute(sql);
} catch (Exception e) {
e.printStackTrace();
}
return rs;
}
@SuppressWarnings("finally")
public static String httpPost(String url,String jsonParam){
DefaultHttpClient client = new DefaultHttpClient();
client.getParams().setParameter(HttpMethodParams.USER_AGENT, "User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:43.0) Gecko/20100101 Firefox/43.0");
HttpPost post = new HttpPost(url);
HttpResponse response = null;
String respStr = "";
if (jsonParam.length() == 0){
client.close();
return "";
}
try {
StringEntity entity = new StringEntity(jsonParam,"utf-8");
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
post.setEntity(entity);
response = client.execute(post);
//获取响应数据
InputStreamReader reader = new InputStreamReader(response.getEntity().getContent(),"UTF-8");
BufferedReader br = new BufferedReader(reader);
String line = null;
StringBuilder sb = new StringBuilder();
while((line = br.readLine())!=null){
sb.append(line);
}
respStr = sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
finally {
client.close();
return respStr;
}
}
/**
* 读取POST请求内容数据.
* HttpServletRequest request
*/
@SuppressWarnings("finally")
public static String getPostContent(HttpServletRequest request) {
BufferedReader br;
String line = null;
StringBuilder sb = null;
String result = "";
try {
InputStreamReader reader = new InputStreamReader(request.getInputStream(),"UTF-8");
br = new BufferedReader(reader);
sb = new StringBuilder();
while((line = br.readLine())!=null){
sb.append(line);
}
result = sb.toString();
}
catch (Exception e)
{
e.printStackTrace();
}
finally {
return result;
}
}
}
静态页面html
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>TCEP</title>
<link rel="stylesheet" type="text/css" href="jquery-easyui-1.5.2/themes/default/easyui.css">
<link rel="stylesheet" type="text/css" href="jquery-easyui-1.5.2/themes/icon.css">
<link rel="stylesheet" type="text/css" href="jquery-easyui-1.5.2/demo/demo.css">
<script type="text/javascript" src="jquery-easyui-1.5.2/jquery.min.js"></script>
<script type="text/javascript" src="jquery-easyui-1.5.2/jquery.easyui.min.js"></script>
</head>
<body>
<div class="easyui-layout" style="width:100%;height:600px;">
<div data-options="region:'north'" style="height:50px; background:#557fc3; color:yellow">
<h2 style="text-align:center;vertical-align:middle;height:30px;margin-bottom:5px;margin-top:13px;">性能测试执行平台</h2>
</div>
<div data-options="region:'west',split:true" title="导航栏" style="width:120px;">
<div class="easyui-accordion" data-options="fit:true,border:false">
<div title="接口MOCK" style="padding:10px;">
<a href="mock.html" style="display:block;width:80px;height:18px;border:1.5px solid #000000;background:#336699;font-size:14px;margin-top:10px;padding: 2px 6px;color:#ffffff;text-decoration:none;"
target="Iframe" onClick='setNavigationBar("接口MOCK", "MOCK管理")'>MOCK管理</a>
</div>
<div title="接口自动化" style="padding:10px;">
</div>
<div title="常用工具" data-options="selected:true" style="padding:10px">
<a href="jsonFormat.html" style="display:block;width:80px;height:18px;border:1.5px solid #000000;background:#336699;font-size:14px;margin-top:10px;padding: 2px 6px;color:#ffffff;text-decoration:none;"
target="Iframe" onClick='setNavigationBar("常用工具", "JSON格式化")'>JSON格式化</a>
</div>
</div>
</div>
<div data-options="region:'center',title:'workspace',iconCls:'icon-ok'">
<iframe id="frame" name="Iframe" frameborder="0" scrolling="no" src="mock.html"
style="width:100%;height:99%;overflow: hidden; border: 0px solid red;">
</iframe>
</div>
</div>
<script>
$(document).ready(function(e)
{
setNavigationBar("接口MOCK", "MOCK管理");
});
/**
* 更改导航栏名称
* @param bar1: 上一层的名称
* @param bar2: 当前层的名称
*/
function setNavigationBar(bar1, bar2)
{
currentFuncName = [];
currentFuncName.push(bar1);
var trHtml = bar1;
if (bar2)
{
currentFuncName.push(bar2);
trHtml += " <b>></b> "+ bar2;
}
getByClass("panel-with-icon")[0].innerHTML=trHtml;;
}
/*
*通过classname获取元素
*
*/
function getByClass(sClass){
var aResult=[];
var aEle=document.getElementsByTagName('*');
for(var i=0;i<aEle.length;i++){
/*将每个className拆分*/
var arr=aEle[i].className.split(/\s+/);
for(var j=0;j<arr.length;j++){
/*判断拆分后的数组中有没有满足的class*/
if(arr[j]==sClass){
aResult.push(aEle[i]);
}
}
}
return aResult;
};
</script>
</body>
</html>
mock.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="jquery-easyui-1.5.2/themes/default/easyui.css">
<link rel="stylesheet" type="text/css" href="jquery-easyui-1.5.2/themes/icon.css">
<link rel="stylesheet" type="text/css" href="jquery-easyui-1.5.2/demo/demo.css">
<script type="text/javascript" src="jquery-easyui-1.5.2/jquery.min.js"></script>
<script type="text/javascript" src="jquery-easyui-1.5.2/jquery.easyui.min.js"></script>
</head>
<body>
<table id="dg" title="MOCK管理" class="easyui-datagrid" style="width:100%;height:100%"
url="mock!getMock.action" toolbar="#toolbar" pagination="true"
rownumbers="true" fitColumns="true" singleSelect="true">
<thead>
<tr>
<th field="interfaceName" width="50">接口服务</th>
<th field="methodName" width="50">接口方法</th>
<th field="paramTypes" width="50">参数类型</th>
<th field="paramJson" width="100">参数JSON</th>
<th field="returnType" width="50">返回类型</th>
<th field="returnJson" width="100">返回JSON</th>
<th field="status" width="45">mock开关(0关,1开)</th>
</tr>
</thead>
</table>
<div id="toolbar">
<a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-add" plain="true" onclick="newMock()">添加mock接口</a>
<a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-edit" plain="true" onclick="editMock()">修改mock接口</a>
<a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-remove" plain="true" onclick="destroyMock()">删除mock接口</a>
</div>
<div id="dlg" class="easyui-dialog" style="width:1000px"
closed="true" buttons="#dlg-buttons">
<form id="fm" method="post" novalidate style="margin:0;padding:20px 50px">
<div style="margin-bottom:20px;font-size:14px;border-bottom:1px solid #ccc">Mock Information</div>
<div style="margin-bottom:10px">
<input name="interfaceName" class="easyui-textbox" required="true" label="接口服务:" style="width:100%">
</div>
<div style="margin-bottom:10px">
<input name="methodName" class="easyui-textbox" required="true" label="接口方法:" style="width:100%">
</div>
<div style="margin-bottom:10px">
<input name="paramTypes" class="easyui-textbox" required="true" label="参数类型:" style="width:100%">
</div>
<div style="margin-bottom:10px">
<input name="paramJson" class="easyui-textbox" required="true" label="参数JSON:" style="width:100%">
</div>
<div style="margin-bottom:10px">
<input name="returnType" class="easyui-textbox" required="true" label="返回类型:" style="width:100%">
</div>
<div style="margin-bottom:10px">
<input name="returnJson" class="easyui-textbox" required="true" label="返回JSON:" style="width:100%">
</div>
<div style="margin-bottom:10px">
<input name="status" class="easyui-textbox" required="true" label="mock开关:" style="width:20%">
<a >请输入0或者1 (0-关闭mock,1-开启mock)</a>
</div>
</form>
</div>
<div id="dlg-buttons" style="text-align:center"">
<a href="javascript:void(0)" class="easyui-linkbutton c6" iconCls="icon-ok" onclick="saveMock()" style="width:90px">Save</a>
<a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-cancel" onclick="javascript:$('#dlg').dialog('close')" style="width:90px">Cancel</a>
</div>
<script type="text/javascript">
var url;
function newMock(){
$('#dlg').dialog('open').dialog('center').dialog('setTitle','New Mock');
$('#fm').form('clear');
url = 'mock!newMock.action';
}
function editMock(){
var row = $('#dg').datagrid('getSelected');
if (row){
$('#dlg').dialog('open').dialog('center').dialog('setTitle','Edit Mock');
$('#fm').form('load',row);
url = 'mock!updateMock.action?id='+row.id;
}
}
function saveMock(){
$('#fm').form('submit',{
url: url,
onSubmit: function(){
return $(this).form('validate');
},
success: function(result){
var result = eval('('+result+')');
if (result.errorMsg){
$.messager.show({
title: 'Error',
msg: result.errorMsg
});
} else {
$('#dlg').dialog('close'); // close the dialog
$('#dg').datagrid('reload'); // reload the user data
}
}
});
}
function destroyMock(){
var row = $('#dg').datagrid('getSelected');
if (row){
$.messager.confirm('Confirm','Are you sure you want to delete this mock?',function(r){
if (r){
$.post('mock!deleteMock.action',{id:row.id},function(result){
if (result.success){
$('#dg').datagrid('reload'); // reload the user data
} else {
$.messager.show({ // show error message
title: 'Error',
msg: result.errorMsg
});
}
},'json');
}
});
}
}
</script>
</body>
</html>
jsonFormat.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script type="text/javascript" src="jquery-easyui-1.5.2/jquery.min.js"></script>
<script type="text/javascript" src="js/common.js"></script>
</head>
<body>
<div>
<textarea id="json_input" style="font-size: 12px !important;width:99%;height:100%" rows="32"
spellcheck="false" placeholder="请输入需要格式化的json字符串"></textarea>
</div>
<div class="left" style="float:left">
<button id="validate" >格式化</button>
<button id="compress" > 压缩 </button>
<button id="compress" onclick="javascript:json_input.value='';$('#json_input').focus();"> 清空 </button>
</div>
<script>
//格式化
$("#validate").click(function(){
var v =$("#json_input").val();
var v1 = format(v,false);
if(v1){
$("#json_input").val(v1);
}
});
//压缩
$("#compress").click(function(){
var v =$("#json_input").val();
var v1 = format(v,true);
if(v1){
$("#json_input").val(v1);
}
});
//json格式化函数
function format(txt,compress/*是否为压缩模式*/){/* 格式化JSON源码(对象转换为JSON文本) */
var indentChar = ' ';
if(/^\s*$/.test(txt)){
openTipWin('数据为空,无法格式化!');
return;
}
try{var data=eval('('+txt+')');}
catch(e){
openTipWin('数据源语法错误,格式化失败!');
return;
};
var draw=[],last=false,This=this,line=compress?'':'\n',nodeCount=0,maxDepth=0;
var notify=function(name,value,isLast,indent/*缩进*/,formObj){
nodeCount++;/*节点计数*/
for (var i=0,tab='';i<indent;i++ )tab+=indentChar;/* 缩进HTML */
tab=compress?'':tab;/*压缩模式忽略缩进*/
maxDepth=++indent;/*缩进递增并记录*/
if(value&&value.constructor==Array){/*处理数组*/
draw.push(tab+(formObj?('"'+name+'":'):'')+'['+line);/*缩进'[' 然后换行*/
for (var i=0;i<value.length;i++)
notify(i,value[i],i==value.length-1,indent,false);
draw.push(tab+']'+(isLast?line:(','+line)));/*缩进']'换行,若非尾元素则添加逗号*/
}else if(value&&typeof value=='object'){/*处理对象*/
draw.push(tab+(formObj?('"'+name+'":'):'')+'{'+line);/*缩进'{' 然后换行*/
var len=0,i=0;
for(var key in value)len++;
for(var key in value)notify(key,value[key],++i==len,indent,true);
draw.push(tab+'}'+(isLast?line:(','+line)));/*缩进'}'换行,若非尾元素则添加逗号*/
}else{
if(typeof value=='string')value='"'+value.replace(/\"/g,"\\\"")+'"'; /* value中双引号加上转移斜杠 */
draw.push(tab+(formObj?('"'+name+'":'):'')+value+(isLast?'':',')+line);
};
};
var isLast=true,indent=0;
notify('',data,isLast,indent,false);
return draw.join('');
}
</script>
</body>
</html>
js
jquery-easyui-1.5.2
common.js
var w;
function openTipWin(message){
var mes = message + '<br/><br/><br/><input type="button" onclick="closeTipWin();" value="关闭"/>';
w = new PopWin(message);
w.setWidthHeight(400,150);
w.show();
}
function closeTipWin(){
w.removeObj();
}
function PopWin(str) {
var msgw, msgh, bordercolor;
msgw = 400;//提示窗口的宽度
msgh = 210;//提示窗口的高度
titleheight = 25 //提示窗口标题高度
bordercolor = "#336699";//提示窗口的边框颜色/标题颜色
bgObj = document.createElement("div");//创建一个div对象(背景层)
msgObj = document.createElement("div")//创建一个div对象(提示框层)
var title = document.createElement("h4");//创建一个h4对象(提示框标题栏)
// 设置对话框的宽和高
this.setWidthHeight = function(w, h) {
msgw = w;
msgh = h;
}
this.show = function() {
var sWidth, sHeight;
sWidth = document.body.offsetWidth;//浏览器工作区域内页面宽度
sHeight = screen.height;//屏幕高度(垂直分辨率)
var scrollTop = document.documentElement.scrollTop;
// if (self.frameElement && self.frameElement.tagName == "IFRAME") {
// if (!self.frameElement.contentDocument) {
// sWidth = self.frameElement.contentDocument.body.offsetWidth;
// sHeight = self.frameElement.contentDocument.body.offsetHeight;
// } else {
// sWidth = self.frameElement.Document.body.offsetWidth;
// sHeight = self.frameElement.Document.body.offsetHeight;
// }
// scrollTop = window.parent.document.documentElement.scrollTop;
// }
//背景层(大小与窗口有效区域相同,即当弹出对话框时,背景显示为放射状透明灰色)
//this.bgObj=document.createElement("div");//创建一个div对象(背景层)
//定义div属性,即相当于
//<div id="bgDiv" style="position:absolute; top:0; filter:progid:DXImagesTransform.Microsoft.Alpha(style=3,opacity=25,finishOpacity=75); opacity:0.6; left:0; width:918px; height:768px; z-index:10000;"></div>
bgObj.setAttribute('id', 'bgDiv');
bgObj.style.position = "absolute";
bgObj.style.top = "0";
bgObj.style.background = "#777";
bgObj.style.filter = "progid:DXImageTransform.Microsoft.Alpha(style=3,opacity=25,finishOpacity=75";
bgObj.style.opacity = "0.6";
bgObj.style.left = "0";
bgObj.style.width = sWidth + "px";
bgObj.style.height = sHeight + "px";
bgObj.style.zIndex = "10000";
document.body.appendChild(bgObj);//在body内添加该div对象
//this.msgObj=document.createElement("div")//创建一个div对象(提示框层)
//定义div属性,即相当于
//<div id="msgDiv" align="center" style=" border:1px solid #336699; position:absolute; left:50%; top:50%; font:12px/1.6em Verdana,Geneva,Arial,Helvetica,sans-serif; margin-left:-225px; margin-top:npx; width:400px; height:100px; text-align:center; line-height:25px; z-index:100001;"></div>
msgObj.setAttribute("id", "msgDiv");
msgObj.setAttribute("align", "center");
msgObj.style.background = "white";
msgObj.style.border = "1px solid " + bordercolor;
msgObj.style.position = "absolute";
msgObj.style.left = "50%";
msgObj.style.top = scrollTop + 150 + "px";
msgObj.style.font = "12px/1.6em Verdana, Geneva, Arial, Helvetica, sans-serif";
msgObj.style.marginLeft = "-225px";
msgObj.style.marginTop = "0px";
msgObj.style.width = msgw + "px";
msgObj.style.height = msgh + "px";
msgObj.style.textAlign = "center";
msgObj.style.lineHeight = "25px";
msgObj.style.zIndex = "10001";
//var title=document.createElement("h4");//创建一个h4对象(提示框标题栏)
//定义h4的属性,即相当于
//<h4 id="msgTitle" align="right" style="margin:0; padding:3px; filter:progid:DXImageTransform.Microsoft.Alpha(startX=20, startY=20, finishX=100, finishY=100,style=1,opacity=75,finishOpacity=100); opacity:0.75; border:1px solid #336699; height:18px; font:12px Verdana,Geneva,Arial,Helvetica,sans-serif; color:white; cursor:pointer;" onclick="">关闭</h4>
title.setAttribute("id", "msgTitle");
title.setAttribute("align", "left");
title.style.margin = "0";
title.style.padding = "3px";
title.style.background = bordercolor;
title.style.filter = "progid:DXImageTransform.Microsoft.Alpha(startX=20, startY=20, finishX=100, finishY=100,style=1,opacity=75,finishOpacity=100);";
title.style.opacity = "0.75";
title.style.border = "1px solid " + bordercolor;
title.style.height = "18px";
title.style.font = "12px Verdana, Geneva, Arial, Helvetica, sans-serif";
title.style.color = "white";
//title.style.cursor="pointer";
title.innerHTML = "错误提示";
//title.onclick=this.removeObj;
var button=document.createElement("input");//创建一个input对象(提示框按钮)
//定义input的属性,即相当于
//<input type="button" align="center" style="width:100px; align:center; margin-left:250px; margin-bottom:10px;" value="关闭">
button.setAttribute("type","button");
button.setAttribute("value","关闭");
button.style.width="60px";
button.style.align="center";
button.style.marginLeft="0px";
button.style.marginBottom="0px";
button.style.background=bordercolor;
button.style.border="1px solid "+ bordercolor;
button.style.color="white";
button.onclick=this.removeObj;
document.body.appendChild(msgObj);//在body内添加提示框div对象msgObj
document.getElementById("msgDiv").appendChild(title);//在提示框div中添加标题栏对象title
var txt = document.createElement("p");//创建一个p对象(提示框提示信息)
//定义p的属性,即相当于
//<p style="margin:1em 0;" id="msgTxt">测试效果</p>
txt.style.margin = "1em 0"
txt.setAttribute("id", "msgTxt");
txt.innerHTML = str + "<br/><br/>";//来源于函数调用时的参数值
document.getElementById("msgDiv").appendChild(txt);//在提示框div中添加提示信息对象txt
document.getElementById("msgDiv").appendChild(button);//在提示框div中添加按钮对象button
}
this.removeObj = function() {//点击标题栏触发的事件
document.body.removeChild(bgObj);//删除背景层Div
document.getElementById("msgDiv").removeChild(title);//删除提示框的标题栏
document.body.removeChild(msgObj);//删除提示框层
}
}
rpc接口mock平台的更多相关文章
- RPC接口mock测试
转载:http://blog.csdn.net/ronghuanye/article/details/71124127 1 简介 Dubbo目前的应用已经越来越广泛.或者基于Dubbo二 ...
- [转] 前后端分离开发模式的 mock 平台预研
引入 mock(模拟): 是在项目测试中,对项目外部或不容易获取的对象/接口,用一个虚拟的对象/接口来模拟,以便测试. 背景 前后端分离 前后端仅仅通过异步接口(AJAX/JSONP)来编程 前后端都 ...
- 这个接口管理平台 eoLinker 开源版部署指南你一定不想错过
本文主要内容是讲解如何在本地部署eoLinker开源版. 环境要求 1.PHP 5.5+ / PHP7+(推荐) 2.Mysql 5.5+ / Mariadb 5.5+ 3.Nginx(推荐) / A ...
- 分享一个开源免费、目前最好的API接口管理平台----eoLinker
一.概况 eoLinker 是目前业内领先.国内最大的在线 API 接口管理平台,提供自动生成 API 文档.API 自动化测试.Mock 测试.团队协作等功能,旨在解决由于前后端分离导致的开发效率低 ...
- (转)Centos下,Docker部署Yapi接口管理平台
接口测试的工具很多,公司引进了接口管理平台Yapi,自己尝试直接搭建,从安装Nodejs到配置MongoDB数据库,再到安装yapi的时候,遇到浏览器打开本地服务器Ip地址后,没有显示部署内容...没 ...
- Centos下,Docker部署Yapi接口管理平台(详细得令人发指)
接口测试的工具很多,公司引进了接口管理平台Yapi,自己尝试直接搭建,从安装Nodejs到配置MongoDB数据库,再到安装yapi的时候,遇到浏览器打开本地服务器Ip地址后,没有显示部署内容...没 ...
- mock平台架构及实现
转载: http://blog.csdn.net/xkhgnc_6666/article/details/51757209 在测试过程中有些情况通过手工测试是无法测试出来的或是非常难复现,比如网络异常 ...
- 这份接口管理平台 eoLinker 开源版的部署指南教程你一定不想错过
本文主要内容是讲解如何在本地部署eoLinker开源版. 环境要求 1.PHP 5.5+ / PHP7+(推荐) 2.Mysql 5.5+ / Mariadb 5.5+ 3.Nginx(推荐) / A ...
- dmock 基于Django的轻量级Mock平台
GitHub:https://github.com/yjlch1016/dmock # dmock 基于Django的轻量级Mock平台 dmock即Django+Mock的缩写 一.思路: mock ...
随机推荐
- OpenGL入门学习(四)
http://blog.csdn.net/sun6255028/article/details/5090055 OpenGL支持两种颜色模式:一种是RGBA,一种是颜色索引模式.无论哪种颜色模式,计算 ...
- Linux Suspend过程【转】
转自:http://blog.csdn.net/chen198746/article/details/15809363 目录(?)[-] Linux Suspend简介 Suspend流程 enter ...
- java基础练习 12
public class Twelfth { /*海滩上有一堆桃子,五只猴子来分.第一只猴子把这堆桃子凭据分为五份,多了一个,这只猴子把多的一个扔入海中,拿走了一份.第二只猴子把剩下的桃子又平均分成五 ...
- zabbix 硬盘健康监控
#!/bin/sh function sh { sd=`ls /dev/ | grep '^sd' |grep -v '[0-9]$'` echo '' > /usr/local/zabbix/ ...
- 6.安装和配置OpenStack图片服务组件
安装和配置图片服务组件 这里是安装在控制器上 安装和配置图片服务组件 yum install –y openstack-glance python-glanceclient 编辑/etc/glance ...
- 更改了mysql的配置文件之后,启动不了mysql服务
更改了mysql的配置文件之后,启动不了mysql服务 mysql数据库error: Found option without preceding group in config file 问题解决 ...
- hdu 3790(SPFA)
最短路径问题 Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Subm ...
- [BZOJ1082][SCOI2005]栅栏 二分+搜索减枝
1082: [SCOI2005]栅栏 Time Limit: 10 Sec Memory Limit: 162 MBSubmit: 2430 Solved: 1034[Submit][Status ...
- C# api基础1
1.创建一个简单的api 目录结构 再创建一个controller用来测试 public class DefaultController : ApiController { public string ...
- #424 Div2 E
#424 Div2 E 题意 给出一个 n 个数的数列,从前往后取数,如果第一个数是当前数列的最小值,则取出,否则将它放到数列尾端,问使数列为空需要多少步操作. 分析 用数据结构去模拟. 线段树维护区 ...