标签:
从事JAVA开发3年了,对java的了解算不上很深入!期间也接触了其他的语言,包括php,Nodejs,Expressjs等语言,让我感触比较深的就是变量的定义,在java中,字符串要用String a;数字要用 int a;小数用 float a; 或者double a; 而php中$a即可定义所有类型的变量,Nodejs和Expressjs中使用var a即可定义所有类型的变量,这里你可能说了java更严谨,而且java也能使用Object a来定义所有变量啊!在java中我相信对于定义一个数字int a=4;而没有人写成Object a =4。
public static void main(String args[]){
ScriptEngine js = new ScriptEngineManager().getEngineByName("javascript");
Bindings bindings= js.getBindings(ScriptContext.ENGINE_SCOPE);
bindings.put("java_out", System.out);
js.eval("var a=‘hello‘;java_out.println(a);");
}
public class JsAction extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
ScriptEngine js = new ScriptEngineManager().getEngineByName("javascript");
Bindings bindings= js.getBindings(ScriptContext.ENGINE_SCOPE);
bindings.put("java_out", System.out);
bindings.put("java_request", request);
bindings.put("java_response", response);
BaseDao dao = new BaseDao();
bindings.put("java_dao", dao);
Extension ext = new Extension(request,response,js);
bindings.put("java_ext", ext);
loadjs(request, js);
}
private void loadjs(HttpServletRequest request,ScriptEngine js){
try {
String path = request.getSession().getServletContext().getRealPath("/"); //获取系统路径
String f = request.getRequestURI().replace(request.getContextPath(), "")+".js";
System.err.println("request -> "+f);
js.eval(new BufferedReader(new InputStreamReader(new FileInputStream(new File(path+"WEB-INF/"+f)),"utf-8")));
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
}
index.js代码如下
java_ext.include("js/config.js");
//json
var obj ={name:"zhangsan",age:"21",sex:"男"};
java_out.println(obj.age);
//put or get
java_ext.put("sex",obj.sex);
java_out.println(java_ext.get("sex"));
//db op
//demo1
var list=java_dao.query("select * from vip limit 0,10",[]);
var map = list.get(0);
java_out.println(map.get("address"));
//demo2
var listcount = java_dao.query("select count(*) as c from vip",[]);
var count = listcount.get(0).get("c");
java_out.println(count);
//demo3
var id=java_dao.execute("insert into test2 (code) values (?)",["nihao"]);
java_out.println(id);
//demo4
var bool = java_dao.transaction(["insert into test2 (code) values (‘zhangsan‘)","insert into test2 (code) values (‘lisi‘)"])
java_out.println(bool);
//go to tpl
java_ext.load("../tpl/index.jsp");
标签:
原文地址:http://blog.csdn.net/qilin001cs/article/details/51328811