JAVA不通过接口传值给Python脚本,可以用Jython实现,Jython是一种完整的语言,而不是一个Java翻译器或仅仅是一个Python编译器,它是一个Python语言在Java中的完全实现。Jython也有很多从CPython中继承的模块库。最有趣的事情是Jython不像CPython或其他任何高级语言,它提供了对其实现语言的一切存取。所以Jython不仅给你提供了Python的库,同时也提供了所有的Java类。
意思就是通过Jython 实现Python和java的互通:
这段程序最终的实现效果如图:
就是通过Python脚本给name的value值加上 ()
1、首先下载Jython 的jar包:(Jython的环境安装教程请参照——百度)
2、JAVA上请求数据库获取到一串JSON 数据,这里我们使用的是原生的JDBC的方式:
JDBC for sqlserver jar包有:
下面是servlet 连接sqlserver 的代码(servlet 如何连接sqlserver的代码 请自行百度,
下面我贴的是doGet部分代码):
public final String sql = "select * from PythonTest";
public String scriptFile = "D:\\eclipseworkspace\\pydev\\python\\";
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
jdbcDao conn = new jdbcDao();
ArrayList list = new ArrayList();
HashMap map = new HashMap();
Connection connection = conn.getConnection();
Statement sta;
try {
sta = connection.createStatement();
ResultSet execute = sta.executeQuery(sql);
ResultSetMetaData metaData = execute.getMetaData();
JSONArray array = new JSONArray();
while(execute.next()){
JSONObject obj = new JSONObject();
getType(execute,metaData, obj);
array.add(obj); //把数据存到JSONArray
//String name = execute.getString("name");
//list.add(name);
}
JavaExecutePython jython = new JavaExecutePython();
JSONArray executJson = jython.executJson(scriptFile, array);
for(int i=0;i
JSONObject obj = JSONObject.fromObject(executJson.get(i));
}
System.out.println("修改后的arrary"+executJson);
//ArrayList list2 = jython.execute(scriptFile,list);
//HashMap executMap = jython.executMap(scriptFile,map);j
//System.out.println("更改后的list里面有:"+array);
conn.close(execute,sta, connection);
} catch (SQLException e) {
e.printStackTrace();
}
}
private void getType(ResultSet rs, ResultSetMetaData rsmd, JSONObject obj)
throws SQLException {
int total_rows = rsmd.getColumnCount();
for (int i = 0; i < total_rows; i++) {
String columnName = rsmd.getColumnLabel(i + 1);
if (obj.has(columnName)) {
columnName += "1";
}
try {
switch (rsmd.getColumnType(i + 1)) {
case java.sql.Types.ARRAY:
obj.put(columnName, rs.getArray(columnName));
break;
case java.sql.Types.BIGINT:
obj.put(columnName, rs.getInt(columnName));
break;
case java.sql.Types.BOOLEAN:
obj.put(columnName, rs.getBoolean(columnName));
break;
case java.sql.Types.BLOB:
obj.put(columnName, rs.getBlob(columnName));
break;
case java.sql.Types.DOUBLE:
obj.put(columnName, rs.getDouble(columnName));
break;
case java.sql.Types.FLOAT:
obj.put(columnName, rs.getFloat(columnName));
break;
case java.sql.Types.INTEGER:
obj.put(columnName, rs.getInt(columnName));
break;
case java.sql.Types.NVARCHAR:
obj.put(columnName, rs.getNString(columnName));
break;
case java.sql.Types.VARCHAR:
obj.put(columnName, rs.getString(columnName));
break;
case java.sql.Types.TINYINT:
obj.put(columnName, rs.getInt(columnName));
break;
case java.sql.Types.SMALLINT:
obj.put(columnName, rs.getInt(columnName));
break;
case java.sql.Types.DATE:
obj.put(columnName, rs.getDate(columnName));
break;
case java.sql.Types.TIMESTAMP:
obj.put(columnName, rs.getTimestamp(columnName));
break;
default:
obj.put(columnName, rs.getObject(columnName));
break;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
3、然后是Jython 部分要写的代码(我们现在要传的是一个JsonArrary):
public class JavaExecutePython {
public PythonInterpreter interpreter;
public JavaExecutePython(){
interpreter = new PythonInterpreter();
Properties props = new Properties();
props.put("python.console.encoding", "UTF-8"); java.nio.charset.UnsupportedCharsetException: cp0.
props.put("python.security.respectJavaAccessibility", "false");
props.put("python.import.site","false");
Properties preprops = System.getProperties();
PythonInterpreter.initialize(preprops, props, new String[0]);
interpreter.exec("import sys");
interpreter.exec("sys.path.append('C:/Program Files/Jython/Lib')");//jython自己的
interpreter.exec("sys.path.append('C:/Program Files/Jython/Lib/site-packages')");//jython 加载脚本的Python的jar包
};
//测试jython是否调用成功
public void test() {
interpreter.exec("days=('mod','Tue','Wed','Thu','Fri','Sat','Sun'); ");
interpreter.exec("print days[1];");
}
//java 向Python传递JSONArray数据
public JSONArray executJson(String url,JSONArray array){
List list = new ArrayList();
interpreter.execfile(url+"my_utils2.py");//加载Py文件
PyFunction func = (PyFunction) interpreter.get("jsonArray",PyFunction.class);//加载Py的方法
PyList pyList = new PyList();
for (int i=0;inew PyString(array.get(i).toString());
pyList.append(obj);
}
PyList pylist = (PyList) func.__call__(pyList);
for (int i=0;ivalue = pylist.get(i).toString();
list.add(value);
}
JSONArray jsonarray = JSONArray.fromObject(list);
return jsonarray;
}
// java 向python 传递HashMap
public HashMap executMap(String url,
HashMap map) {
interpreter.execfile(url + "my_utils2.py");
PyFunction func = (PyFunction) interpreter.get("adder",
PyFunction.class);
PyDictionary pyDict = new PyDictionary();
for (String key : map.keySet()) {
PyString key1 = new PyString("" + key + "");
pyDict.__setitem__(key1, new PyString("" + map.get(key) + ""));
}
PyDictionary pyobj = (PyDictionary) func.__call__(pyDict);
ConcurrentMap map2 = pyobj.getMap();
for (PyObject key : map2.keySet()) {
String value = map2.get(key).toString();
try {
map.put(key.toString(), new String(
value.getBytes("ISO-8859-1"), "utf-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
return map;
}
}
4、接下来是Python 脚本的代码:
Python脚本都是以Py后缀名结尾的我把它放在 D:\eclipseworkspace\pydev\python\my_utils2.py
# coding=UTF-8
import simplejson as json
import sys
reload(sys)
def jsonArray(xx):
list =[];
dict = {};
for i in range(0, len(xx)):
b = eval(xx[i]) #转换成字典
b['name'] = "("+b['name']+")" #加上()
b = str(b)
python_object = json.dumps(b,ensure_ascii=False, encoding="utf-8");
#python_object = json.loads(python_object)
list.append(python_object)
return list #返回的是一个列表
这样就可以把处理过的 jsonarray 传回给java了,实现Java 和 Python 互连 注意的地方(中文乱码问题Python 返回给Java的时候中文会变成ISO-8859-1 要转码成UTF-8 才能正确显示)