转载: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 >
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 )[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 >
        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 :'):'')+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 ).removeChild(title);//删除提示框的标题栏
document.body.removeChild(msgObj);//删除提示框层
}
}

相关文章:

  • 2022-12-23
  • 2021-09-03
  • 2022-12-23
  • 2021-12-19
  • 2022-12-23
  • 2021-10-16
  • 2021-11-01
  • 2021-12-08
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-10-05
  • 2022-12-23
  • 2022-12-23
  • 2021-08-07
相关资源
相似解决方案