|
下面 (?alt+shift+T ) 中都可以找到 1.改名 :??(?alt+shift+R ) 2.類移動(dòng):(?alt+shift+V ) 3.方法上移父類,下移子類 (alt+shift+T) + U/D 4.方法接口化? (alt+shift+T) +T 5.部分代碼提升為方法 alt+shift+M 6.局部變量提升為類變量 alt+shift+F
.............
***************************************************************
Ctrl+M: ? 工作區(qū)最大化/最小化 ? ? Alt+/: ? ? 智能提示 ? ? F3: ? ? ? ? ? 察看聲明 ? ? Crtl+1: ? 修正錯(cuò)誤 ? ? ? ? Shift+Alt+T: ? 重構(gòu) ? ? Shift+Alt+M: ? 提取函數(shù) ? ? Shift+Alt+R: ? 重命名 ? ? Shift+Alt+C: ? 更改函數(shù)標(biāo)記 ? ? ? ? Ctrl+Shitf+F: ? 格式化代碼 ?
在WEB開發(fā)中 測(cè)試 在 C/S? 而 實(shí)際運(yùn)行 B/S 造成配置文件 在硬編碼時(shí)總是改 。 但看 hibernate 的配置文件 確可以很好工作 ,沒辦法讀源碼 在框架中 發(fā)現(xiàn) ConfigHelper類起到了作用 。 結(jié)合自己開發(fā)需求,寫出了自己的 帶查詢文件功能類 擴(kuò)展的主要部分在 findFile方法 這用了一下 簡(jiǎn)單的數(shù)據(jù)結(jié)構(gòu)有興趣的可以看看 ? 測(cè)試: 文件skynet.xml
<?xml?version="1.0"?encoding="UTF-8"?> <xml-body> ????<man?id='1'> ????????<name>劉凱毅</name> ????????<avg>24</avg> ????</man> ????<man?id='2'> ????????<name>heha</name> ????????<avg>25</avg> ????</man> </xml-body>
測(cè)試類
package?test.config;
import?org.apache.commons.jxpath.JXPathContext; import?org.apache.commons.jxpath.XMLDocumentContainer;
import?junit.framework.TestCase;
public?class?SkynetConfigTest?extends?TestCase?{
????protected?void?setUp()?throws?Exception?{ ????????super.setUp(); ????} ???? ????public?void?testConfigFile(){ ????????System.out.println( ????????????????//find?file?in?System?user.dir?->?skynet.xml?? ????????????????SkynetConfig.getResourceAsFile(System.getProperty("user.dir")?,? ????????????????????????"skynet.xml").getPath() ????????); ????????System.out.println( ????????????????//find?file?in?System?java.class.path?->?skynet.xml? ????????????SkynetConfig.getResourceAsFile(System.getProperty("java.class.path")?,? ????????????????????"skynet.xml").getPath()? ????????); ????} ????public?void?testConfigURL(){ ????????????JXPathContext?jx?=?JXPathContext.newContext(new?XMLDocumentContainer(? ????????????????????//?in?System?user.dir,java.class.path?find??url:skynet ????????????????????SkynetConfig.getResourceAsURL("skynet.xml")??? ????????????????)); ????????????System.out.println(?jx.getValue("//man[avg='24']/@id")?); ????????????System.out.println(?jx.getValue("//man[avg='24']/name")?); ????} ???? ????public?void?testConfigStream(){ ????????System.out.println(?SkynetConfig.getResourceAsStream("skynet.xml")?); ????} }
結(jié)果: E:\src3\rlzy15\lmisWeb\WEB-INF\classes\test\config\skynet.xml E:\src3\rlzy15\lmisWeb\WEB-INF\classes\test\config\skynet.xml 1 劉凱毅 java.io.FileInputStream@1551d7f
SkynetConfig 類package?test.config;
import?java.io.File; import?java.io.FileInputStream; import?java.io.InputStream;
import?java.net.URL;
import?org.apache.commons.jxpath.JXPathContext; import?org.apache.commons.jxpath.XMLDocumentContainer; import?org.hibernate.util.ConfigHelper;
public?class?SkynetConfig?{ ???? ????public?static?final?URL?getResourceAsURL(final?String?path)?{ ????????URL?url?=?null;
????????//?First,?try?to?locate?this?resource?through?the?current ????????//?context?classloader. ????????ClassLoader?contextClassLoader?=?Thread.currentThread().getContextClassLoader(); ????????if?(contextClassLoader!=null)?{ ????????????url?=?contextClassLoader.getResource(path); ????????} ????????if?(url?!=?null) ????????????return?url;
????????//?Next,?try?to?locate?this?resource?through?this?class's?classloader ????????url?=?ConfigHelper.class.getClassLoader().getResource(path); ????????if?(url?!=?null) ????????????return?url; ???????? ????????//?Next,?try?to?locate?this?resource?through?the?system?classloader ????????url?=?ClassLoader.getSystemClassLoader().getResource(path); ????????if(url?!=null) ????????????return?url; ???????? ????????File?ff?=?getResourceAsFile(System.getProperty("user.dir")?,path); ????????if(ff==null) ????????????ff?=?getResourceAsFile(System.getProperty("java.class.path")?,?path); ????????try?{ ????????????url?=?new?URL("file:/"+ff.getPath()); ????????}?catch?(Exception?e)?{e.printStackTrace();} ???????? ????????return?url; ????} ???? ????public?static?InputStream?getResourceAsStream(final?String?resource)?{ ????????String?stripped?=?resource.startsWith("/")??? ????????????????resource.substring(1)?:?resource; ????????InputStream?stream?=?null;? ????????ClassLoader?classLoader?=?Thread.currentThread().getContextClassLoader(); ????????if?(classLoader!=null)?{ ????????????stream?=?classLoader.getResourceAsStream(?stripped?); ????????} ????????if?(?stream?==?null?)?{ ????????????SkynetConfig.class.getResourceAsStream(?resource?); ????????} ????????if?(?stream?==?null?)?{ ????????????stream?=?SkynetConfig.class.getClassLoader().getResourceAsStream(?stripped?); ????????} ????????if?(?stream?==?null?)?{ ????????????File?ff?=?getResourceAsFile(System.getProperty("user.dir")?,resource); ????????????if(ff==null) ????????????????ff?=?getResourceAsFile(System.getProperty("java.class.path")?,?resource); ????????????try?{ ????????????????stream?=?new?FileInputStream(ff); ????????????????if(stream==null) ????????????????????throw?new?Exception(?resource?+?"?not?found"?); ????????????}?catch?(Exception?e)?{e.printStackTrace();} ????????} ????????return?stream; ????} ???? ????public?static?File?getResourceAsFile(String?str,String?findff){ ????????String[]?sfd?=?str.split(";"); ????????for(int?i=0;i<sfd.length;i++){ ????????????File?file?=?new?File(sfd[i]); ????????????if(?file.isDirectory()){ ????????????????File[]?cfs?=?file.listFiles(); ????????????????for(int?j=0;j<cfs.length;j++){ ????????????????????File?ff?=?findFile(cfs[j],findff); ????????????????????if(ff==null)continue; ????????????????????else?return?ff; ???????????????????? ????????????????} ????????????} ????????} ????????return?null?; ????} ???? ????private?static?File?findFile(File?file,String?findff){ ????????if(file.isFile()?&&?file.exists()?&&?isFileEqu(file,findff)??)?return?file?; ????????else?if(?file.isDirectory()?){ ????????????File[]?cfs?=?file.listFiles(); ????????????for(int?i=0;i<cfs.length;i++){ ????????????????File?ff?=?findFile(cfs[i],findff); ????????????????if(ff==null)continue; ????????????????if(?isFileEqu(ff,findff)?){ ????????????????????return?ff; ????????????????} ????????????} ????????} ????????return?null?; ????} ???? ????private?static?boolean?isFileEqu(File?ff,String?findff){ ????????String?path?=?ff.getPath().trim()?; ????????String?findfft?=?findff.trim()?; ???????? ????????if(?path.lastIndexOf(?findfft?)>0)return?true; ???????? ????????return?false; ????}
}
為我準(zhǔn)備學(xué)習(xí)和理解spring 特留下代碼筆記: 參考:http://dev.csdn.net/author/labile/e70c97cb7f504d35b7b5350e7810cc5a.html代碼感想: ??? 沒個(gè)方法都或多或少需要環(huán)境參數(shù)(如: jdbc的conn ,hbn的session...等等 ),方法結(jié)束后又要關(guān)閉。 何不用proxy代理并用配置文件的方法來 關(guān),開session 等 如:以下是我的想法并不是實(shí)際可用 ??? 配置: <class?name="HelloWorldImpl"> ? <function?name="set*" />
? <function?name="getName"> ??? <proxyBegin artt="name" value="liukaiyi"/> ??? ??? //使用Proxy來賦值 name那在實(shí)現(xiàn)代碼中就可以不用去關(guān)注象 session 等屬性的開關(guān)了 ??? ??? //proxy中配置下 , 在實(shí)現(xiàn)類中 就使用 就可以了 ??? <proxyBegin?ref="HelloWorldHandler.doBefter"?args="null"/> ??? <proxyEnd?ref="HelloWorldHandler.doAfter"?args="null"/> ? </function>
? <function?=?name="sayHelloWorld"> ??? <proxyEnd?ref="HelloWorldHandler.doAfter"?args="null"/> ? </function> </class>
代碼: HelloWorld hw = (HelloWorld)Factory.getBean("HelloWorldImpl"); hw.getName();
結(jié)果是: before method invoke! 劉凱毅 after method invoke!
在此 我只是想象,spring 還沒有看,但我認(rèn)為spring 這個(gè)著名的框架應(yīng)該在這方面有很好的實(shí)現(xiàn)。
實(shí)際代碼:希望spring可以向我上面的方法配置好用來取代下面的實(shí)際代碼 ^_^
package?test.proxy;
import?java.lang.reflect.InvocationHandler; import?java.lang.reflect.Method; import?java.lang.reflect.Proxy;
import?junit.framework.TestCase;
public?class?TestProxy?extends?TestCase?{ ???? ????protected?void?setUp()?throws?Exception?{ ????????super.setUp(); ????} ???? ????public?void?testProxy(){ ?????????????HelloWorld?hw?=?new?HelloWorldImpl();??????????? ???????????????????????InvocationHandler?handler?=?new?HelloWorldHandler(hw);?????????? ???????????????????????HelloWorld?proxy?=?(HelloWorld)?Proxy.newProxyInstance(??? ?????????????????????????????????????hw.getClass().getClassLoader(),??? ?????????????????????????????????????hw.getClass().getInterfaces(),??? ?????????????????????????????????????handler);??? ???????????????????????proxy.sayHelloWorld(); ??????????????????????? ???????????????????????System.out.println(); ???????????????????????proxy.setName("liukaiyi"); ???????????????????????proxy.getName(); ????} ???? }
interface?HelloWorld?{??? ????void?sayHelloWorld()?;??? ????void?getName(); ????void?setName(String?name); }
class?HelloWorldImpl?implements?HelloWorld?{??? ????private?String?name?=?""; ????public?void?setName(String?name)?{ ????????this.name?=?name; ????}
????public?void?sayHelloWorld()?{??? ????????System.out.println("Hello?World!");?????????????? ????}
????public?void?getName()?{ ????????System.out.println(this.name); ????}??? }
class?HelloWorldHandler?implements?InvocationHandler?{??? ????????????//要代理的原始對(duì)象??? ????????????private?Object?objOriginal;??? ????????????/**?? ?????????????*?構(gòu)造函數(shù)。?? ?????????????*?@param?obj?要代理的原始對(duì)象。?? ?????????????*/?? ????????????public?HelloWorldHandler(Object?obj)?{??? ???????????????????this.objOriginal?=?obj?;??? ????????????}??? ????????????public?Object?invoke(Object?proxy,?Method?method,?Object[]?args)??? ??????????????????????????throws?Throwable?{??????????????? ???????????????????Object?result?=?null?;?????????????? ???????????????????String?meName?=?method.getName(); ???????????????????if(meName.indexOf("set")>-1?){ ???????????????????????return?method.invoke(this.objOriginal?,args);??? ???????????????????} ???????????????????if(?meName.equals("getName")?){ ????????????????????//方法調(diào)用之前??? ???????????????????????????doBefore();?//仿佛是AOP的影子,呵呵??? ???????????????????} ?????????????????????//調(diào)用原始對(duì)象的方法??? ???????????????????????????result?=?method.invoke(this.objOriginal?,args);??? ?????????????????????//方法調(diào)用之后??? ???????????????????????????doAfter();??????? ??????????????????? ???????????????????return?result?;??? ????????????}??? ????????????private?void?doBefore()?{??? ???????????????????System.out.println("before?method?invoke!");??? ????????????}??? ????????????private?void?doAfter()?{??? ???????????????????System.out.println("after?method?invoke!");??? ????????????}??? ?????}???
結(jié)果: Hello World! after method invoke!
before method invoke! 劉凱毅 after method invoke!
在 D2D 論壇中見 一文標(biāo)題 《在java中利用動(dòng)態(tài)編譯實(shí)現(xiàn)eval》 http://dev2dev.bea.com.cn/bbsdoc/20060724298.html 雖然給出代碼不能運(yùn)行 但標(biāo)題的意思已經(jīng)達(dá)到 在此 我也不多說了 在此完善下原作者的代碼 并使可運(yùn)行來方便大家理解
企圖說明: 代碼的可用性是沒有的,但代碼向我們打開了一個(gè)使java動(dòng)態(tài)編譯的一向大門 有想法的程序員們。我們?cè)诖说玫搅耸裁矗?br /> 代碼說明: ??? 1.為了使用例子的方便 testJavac.java 是 Bean ( name , avg ) 也是 邏輯類 ( eval(string) ) ??? 2.運(yùn)行請(qǐng)?jiān)?classpath 加入 java\lib\tools.jar jar 包 ( com.sun.tools.javac.Main ) ??? 3.還是方便運(yùn)行本例對(duì) 自己在什么 path 并不在意 類中使用了 System.getProperty("user.dir")
import?java.io.File; import?java.io.FileWriter; import?java.io.PrintWriter; import?java.lang.reflect.Method;
import?com.sun.tools.javac.Main;
public?class?testJavac{ ????????public?String?getName(){ ???????????return?"劉凱毅"; ????????} ????????public?int?getAvg(){ ???????????return?24; ????????} ???????? ????????public?Object?eval(String?str)throws?Exception{ ???????????//生成java文件 ????????String?s?=?"class?Temp{"; ????????????s?+=?"private?testJavac?tj?=?new?testJavac();"; ????????????s?+=?"public?String?rt(){"; ????????????s?+=?"?return??\"\"+tj."+str+"();"??; ????????????s?+=?"}"; ????????????s?+="}"; ???????????? ???????????File?f?=?new?File(System.getProperty("user.dir")+"\\Temp.java"); ???????????PrintWriter?pw?=?new?PrintWriter(new?FileWriter(f)); ???????????pw.println(s); ???????????pw.close(); ???????????//動(dòng)態(tài)編譯 ???????????Main?javac?=?new?Main(); ???????????String[]?cpargs?=?new?String[]?{"-d",?System.getProperty("user.dir")?,"Temp.java"}; ???????????int?status?=?javac.compile(cpargs); ???????????if(status!=0){ ??????????????System.out.println("沒有成功編譯源文件!"); ??????????????return?null; ???????????} ???????????//調(diào)用Temp的rt方法返回結(jié)果: ???????????ClassLoader?mc?=?this.getClass().getClassLoader(); ??????????? ???????????Class?clasz?=?mc.loadClass("Temp");
???????????Method?rt?=?clasz.getMethod("rt",?new?Class[]{}); ???????????return?rt.invoke(clasz.newInstance(),?new?Object[]?{?}); ???????????//如果方法沒有返回就直接調(diào)用 ????????} ???????? ???????? ????public?static?void?main(String[]args)throws?Exception{ ????????testJavac?jj?=?new?testJavac(); ????????System.out.println(?jj.eval(args[0])?); ????}
} 運(yùn)行結(jié)果 D:\javac>javac -classpath D:\java\lib\tools.jar;. testJavac.java
D:\javac>java -classpath D:\java\lib\tools.jar;. testJavac getName 劉凱毅 //此時(shí)在當(dāng)前目錄下你可以看到 多了一個(gè) Temp.java 和 Temp.class 文件 //再使用 CalssLoader.loadClass方法動(dòng)態(tài)加載到運(yùn)行環(huán)境中來 //創(chuàng)建 動(dòng)態(tài)? 加載 動(dòng)態(tài)?? (java 動(dòng)起來了) D:\javac>java -classpath D:\java\lib\tools.jar;. testJavac getAvg 24
參照:
??? http://json-lib.sourceforge.net/usage.html先 json <-> object package?test.json;
import?java.util.ArrayList; import?java.util.HashMap; import?java.util.List; import?java.util.Map;
import?org.apache.commons.beanutils.PropertyUtils;
import?com.jjm.viewBean.reportTableBean;
import?net.sf.json.JSONArray; import?net.sf.json.JSONFunction; import?net.sf.json.JSONObject;
import?junit.framework.TestCase;
public?class?JsonTest?extends?TestCase?{
//?object?to?json?************************************************************ ????public?void?testList(){ ????????boolean[]?boolArray?=?new?boolean[]{true,false,true};??? ????????????JSONArray?jsonArray1?=?JSONArray.fromObject(?boolArray?);??? ????????????System.out.println(?jsonArray1?);??? ????????????//?prints?[true,false,true]?? ???????????? ????????????List?list?=?new?ArrayList();??? ????????????list.add(?"first"?);??? ????????????list.add(?"second"?);??? ????????????JSONArray?jsonArray2?=?JSONArray.fromObject(?list?);??? ????????????System.out.println(?jsonArray2?);??? ????????????//?prints?["first","second"]??
????????????JSONArray?jsonArray3?=?JSONArray.fromObject(?"['json','is','easy']"?);??? ????????????System.out.println(?jsonArray3?);??? ????????????//?prints?["json","is","easy"]??? ????} ???? ????public?void?testMap(){ ????????Map?map?=?new?HashMap();??? ?????????map.put(?"name",?"json"?);??? ?????????map.put(?"bool",?Boolean.TRUE?);??? ????????? ?????????map.put(?"int",?new?Integer(1)?);??? ?????????map.put(?"arr",?new?String[]{"a","b"}?);??? ?????????map.put(?"func",?"function(i){?return?this.arr[i];?}"?);??? ?????????JSONObject?json?=?JSONObject.fromObject(?map?);??? ?????????System.out.println(?json?);??? ?????????//{"func":function(i){?return?this.arr[i];?},"arr":["a","b"],"int":1,"name":"json","bool":true} ????}
????/** ?????*?Bean.java? ????????private?String?name?=?"json";??? ????????private?int?pojoId?=?1;??? ????????private?char[]?options?=?new?char[]{'a','f'};??? ????????private?String?func1?=?"function(i){?return?this.options[i];?}";??? ????????private?JSONFunction?func2?=?new?JSONFunction(new?String[]{"i"},"return?this.options[i];"); ????*/ ?????public?void?testBean(){ ?????????JSONObject?jsonObject?=?JSONObject.fromObject(?new?JsonBean()?);??? ?????????System.out.println(?jsonObject?);??? ?????????//{"func1":function(i){?return?this.options[i];?},"pojoId":1,"name":"json","options":["a","f"],"func2":function(i){?return?this.options[i];?}}?? ?????} ????? ?????/** ??????*?private?int?row?; ??????????private?int?col?; ??????????private?String?value?; ??????* ??????*/ ?????public?void?testBeans(){ ?????????List?list?=?new?ArrayList(); ?????????JsonBean2?jb1?=?new?JsonBean2(); ?????????jb1.setCol(1); ?????????jb1.setRow(1); ?????????jb1.setValue("xx"); ????????? ?????????JsonBean2?jb2?=?new?JsonBean2(); ?????????jb2.setCol(2); ?????????jb2.setRow(2); ?????????jb2.setValue(""); ????????? ????????? ?????????list.add(jb1); ?????????list.add(jb2); ????????? ?????????JSONArray?ja?=?JSONArray.fromObject(list); ?????????System.out.println(?ja.toString()?); ?????????//[{"value":"xx","row":1,"col":1},{"value":"","row":2,"col":2}] ?????} ????? ?????
//????json??to?object?************************************************************????? ????? ?????public?void?testJsonBeanUtil()throws?Exception{ ?????????????String?json?=?"{name=\"json\",bool:true,int:1,double:2.2,func:function(a){?return?a;?},array:[1,2]}";??? ????????????JSONObject?jsonObject?=?JSONObject.fromString(json);??? ????????????Object?bean?=?JSONObject.toBean(?jsonObject?);??? ????????????assertEquals(?jsonObject.get(?"name"?),?PropertyUtils.getProperty(?bean,?"name"?)?);??? ????????????assertEquals(?jsonObject.get(?"bool"?),?PropertyUtils.getProperty(?bean,?"bool"?)?);??? ????????????assertEquals(?jsonObject.get(?"int"?),?PropertyUtils.getProperty(?bean,?"int"?)?);??? ????????????assertEquals(?jsonObject.get(?"double"?),?PropertyUtils.getProperty(?bean,?"double"?)?);??? ????????????assertEquals(?jsonObject.get(?"func"?),?PropertyUtils.getProperty(?bean,?"func"?)?);??? ????????????List?expected?=?JSONArray.toList(?jsonObject.getJSONArray(?"array"?)?);??? ????????????assertEquals(?expected,?(List)?PropertyUtils.getProperty(?bean,?"array"?)?);?? ?????} ????? ?????public?void?testJsonBean(){ ?????????????String?json?=?"{\"value\":\"xx\",\"row\":1,\"col\":1}";??? ????????????JSONObject?jsonObject?=?JSONObject.fromString(json); ????????????JsonBean2?bean?=?(JsonBean2)?JSONObject.toBean(?jsonObject,?JsonBean2.class?);??? ????????????assertEquals(?jsonObject.get(?"col"?),new?Integer(?bean.getCol())??);??? ????????????assertEquals(?jsonObject.get(?"row"?),?new?Integer(?bean.getRow()?)?);??? ????????????assertEquals(?jsonObject.get(?"value"?),?bean.getValue()?);?? ?????} }??? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ???
json <-> xmlJSON to XML- JSONObject?json?=?new?JSONObject(?true?);??
- String?xml?=?XMLSerializer.write(?json?);??
| - <o?class="object"?null="true">??
- ??????
| - JSONObject?json?=?JSONObject.fromObject("{\"name\":\"json\",\"bool\":true,\"int\":1}");??
- String?xml?=?XMLSerializer.write(?json?);??
| - <o?class="object">??
- ???<name?type="string">json</name>??
- ???<bool?type="boolean">true</bool>??
- ???<int?type="number">1</int>??
- </o>??
| - JSONArray?json?=?JSONArray.fromObject("[1,2,3]");??
- String?xml?=?XMLSerializer.write(?json?);??
| - <a?class="array"<??
- ???<e?type="number">1</e>??
- ???<e?type="number">2</e>??
- ???<e?type="number">3</e>??
- </a>??
| xml to json - <a?class="array">??
- ??<e?type="function"?params="i,j">??
- ??????return?matrix[i][j];??
- ??</e>??
- </a>??
- JSONArray?json?=?(JSONArray)?XMLSerializer.read(?xml?);??
- System.out.println(?json?);??
- ?
約定:
??? bean.getXX.. 稱為 gbean ??? bean.setXX.. 稱為 sbean 目的: gbean 多屬性 付值給 sbean 多屬性(并值有一定修改后)等復(fù)雜賦 值 用 一句 *邏輯string* 就可以了 多屬性不同類型 賦值了說明:1.sbean : testData 類有4個(gè)屬性 ??? personid ; workno ; hname ; dob ; 2.gbean 類我這用的是數(shù)據(jù)庫動(dòng)態(tài)類 ,有興趣的可以看看我的另一遍blog 動(dòng)態(tài)面向?qū)ο髷?shù)據(jù)庫操作??? 數(shù)據(jù)庫 表 z_jcyy_basepersonnel 多屬性 但 personid,workno,hname 不可以為空 3.這里 get set 賦值 使用的工具 LGUtil測(cè)試:
package?myGGUtil.LGBeanUtil.test;
import?java.util.Date; import?java.util.Iterator; import?java.util.List; import?org.apache.commons.beanutils.BeanUtils; import?org.apache.commons.jxpath.JXPathContext; import?myGGUtil.DBUtil.DyanDBUtils.DyanDBUtils; import?myGGUtil.LGBeanUtil.LGUtil; import?myGGUtil.LGBeanUtil.SpecialAttFun; import?junit.framework.TestCase;
public?class?test?extends?TestCase?{ ???
??? //只有一條數(shù)據(jù)的 一對(duì)一 ????public?void?testONE_TO_ONE()throws?Exception{
??? ??? //得到修改的 數(shù)據(jù)'0301003300' dob 時(shí)間為當(dāng)前 一條值 ????????DyanDBUtils?dyd?=?new?DyanDBUtils(); ????????List?list?=?dyd.select("select?t.*?from?z_jcyy_basepersonnel?t?where?t.personid?=?'0301003300'"); ????????BeanUtils.setProperty(?list.get(0)?,"dob",new?Date());? ????????dyd.updateOrInsert(list.get(0)); ????????List?listD?=?dyd.select("select?t.*?from?z_jcyy_basepersonnel?t?where?t.personid?=?'0301003300'");
??? ??? //這使用 LGutil 目的是 包, 把 數(shù)據(jù)'0301003300'的 personid,workno,hname,dob 值通過一定邏輯賦值 ????????LGUtil?lb?=?new?LGUtil(); ????????lb.setDataList(listD);?? //數(shù)據(jù)加入? : 就是 gbean ????????lb.setMapping(LGUtil.ONE_TO_ONE);?? //定義是一對(duì)一 get -> set ????????lb.setVbClass(testData.class); // sbean 類 ????????lb.setAttrLg(Date.class,"?./${.+}?","action:date($this,'yy-MM-dd')"); ??? ??? //把gbean數(shù)據(jù)為Date類型的付值給 sbean 的string類型 并以 'yy-MM-dd'時(shí)間字符格式 ? ????????lb.setAttrLg(String.class,"./${.+}"); //String 普通付值 ???????? ????????lb.setFun(new?SpecialAttFun(){ ????????????public?void?action(JXPathContext?temD,?JXPathContext?temV,?int?step,?JXPathContext?all)?{ ????????????????temV.setValue("hname","heha"?); //在特殊值 hname 改為 heha (呵哈 我的口號(hào)哦^_^) ????????????} ????????}); ???????? ????????testData?oo?=?(testData)lb.getVBean().get(0)?; ??? ??? //sbean 的值輸出 : ????????System.out.println(oo.getPersonid()+":"+oo.getHname()+":"+oo.getWorkno()+":"+?oo.getDob()?); ??????? ??? ??? //測(cè)試結(jié)束 數(shù)據(jù)庫 改回去 dob 為空 ????????BeanUtils.setProperty(?list.get(0)?,"dob",null);? ????????dyd.updateOrInsert(list.get(0)); ????} ??? ??? //多條數(shù)據(jù)的多對(duì)一? :就是 gbean多 -> sbean ????public?void?testMANY_TO_ONE()throws?Exception{ ????????DyanDBUtils?dyd?=?new?DyanDBUtils(); ????????List?list?=?dyd.select("select?t.*?from?z_jcyy_basepersonnel?t?where?t.personid?like?'03010033%'?"); ??? ??? // 得到多條數(shù)據(jù)
????????LGUtil?lb?=?new?LGUtil(); ????????lb.setDataList(list); ????????lb.setMapping(LGUtil.MANY_TO_ONE); ????????lb.setVbClass(testData.class); ????????lb.setAttrLg("sum(./${workno})");? //把屬性 workno 的全部值 向加 并 付值給 sbean.workno ???????? ????????testData?oo?=?(testData)lb.getVBean().get(0)?; ????????System.out.println(oo.getWorkno()); //輸出 workno ????}
??? //多數(shù)據(jù)的一對(duì)一? gbean多 -> sbean多 ????public?void?testOne_to_one()throws?Exception{ ????????DyanDBUtils?dyd?=?new?DyanDBUtils(); ????????List?listd?=?dyd.select("select?t.*?from?z_jcyy_basepersonnel?t?where?t.personid?=?'0301003300'"); ????????BeanUtils.setProperty(?listd.get(0)?,"dob",new?Date());? ????????dyd.updateOrInsert(listd.get(0)); ????????List?list?=?dyd.select("select?t.*?from?z_jcyy_basepersonnel?t?where?t.personid?=?'0301003300'"); ??? ?? //這 030100330 數(shù)據(jù)改值 下面 展現(xiàn)需要 (有不同哦) ??? ?? ????????LGUtil?lb?=?new?LGUtil(); ????????lb.setDataList(dyd.select("select?t.dob,?t.*?from?z_jcyy_basepersonnel?t?where?t.personid?like?'03010033%'"))?; ????????lb.setMapping(LGUtil.ONE_TO_ONE); ????????lb.setVbClass(testData.class); ???????? ????????lb.setAttrLg("${.+}");//全付值? ??????? lb.setAttrLg(Date.class," ./${.+} ","action:date($this,'yy-MM-dd')"); //date 給格式
????????for(Iterator?it=lb.getVBean().iterator();it.hasNext();?){ ????????????testData?oo?=?(testData)it.next(); ????????????System.out.println(oo.getPersonid()+":"+oo.getHname()+":"+oo.getWorkno()+":"+?oo.getDob()?); ????????} ???????? ????????BeanUtils.setProperty(?list.get(0)?,"dob",null);? ????????dyd.updateOrInsert(list.get(0)); ????}? }
結(jié)果:
//方法 testONE_TO_ONE(): dob為'yy-MM-dd' 0301003300:heha:3300:07-09-29
//方法testMANY_TO_ONE() workno 全加 就是方法3 的workno全加 (大家可以看看哦) 174005.0 //方法testOne_to_one() 全付值 (簡(jiǎn)單展示 也可以對(duì)沒個(gè)屬性修改付 如:dob 方法一樣) 0301003300:張金棟:3300:07-09-29 0301003301:谷嘉奇:3301:78-09-21 0301003302:閆國(guó)春:3302:78-12-24 0301003304:解國(guó)強(qiáng):3304:77-08-17 0301003305:任志勇:3305:71-10-20 0301003306:張寧:3306:74-10-13 0301003307:閆立文:3307:70-07-05 0301003308:鄧志山:3308:74-02-28 0301003309:劉承謙:3309:67-12-30 0301003310:郭愛軍:3310:75-11-21 0301003312:楊濤:3312:73-08-01 0301003313:喬迎松:3313:74-05-27 0301003314:徐志斌:3314:69-03-14 0301003323:黃向東:3323:72-07-30 0301003324:高國(guó)良:3324:73-11-17 0301003326:高杰:3326:74-02-10 0301003329:葛燕京:3329:74-10-29 0301003331:趙震:3331:75-01-07 0301003333:郝君平:3333:74-03-12 0301003339:孫雪峰:3339:73-03-28 0301003340:劉紹明:3340:74-12-23 0301003341:郭金江:3341:73-06-07 0301003342:趙福軍:3342:74-01-17 0301003343:劉勇:3343:74-07-04 0301003349:鄭巖:3349:73-11-29 0301003350:周勇:3350:75-06-03 0301003352:許東波:3352:73-11-30 0301003353:于華濤:3353:71-11-08 0301003354:陳建宏:3354:71-11-21 0301003355:王福祿:3355:70-11-16 0301003357:曹小軍:3357:75-09-05 0301003358:耿龍:3358:76-04-09 0301003359:麻然松:3359:74-04-05 0301003361:侯亮:3361:77-11-01 0301003362:翁寶重:3362:73-10-06 0301003364:李結(jié):3364:74-12-08 0301003367:張建杰:3367:70-01-03 0301003369:王琪:3369:76-03-23 0301003370:劉洪濤:3370:77-10-26 0301003371:張兆鵬:3371:76-06-21 0301003373:王飛虎:3373:74-12-06 0301003375:王愛軍:3375:74-01-02 0301003376:李小發(fā):3376:72-12-20 0301003377:楊京海:3377:78-08-12 0301003379:王羽:3379:77-10-27 0301003380:周鳳昆:3380:74-02-16 0301003381:王建新:3381:76-05-11 0301003384:盧紅峰:3384:77-11-03 0301003387:解瑞杰:3387:72-05-15 0301003390:李振盈:3390:76-10-03 0301003393:馬強(qiáng):3393:75-10-03 0301003397:齊永強(qiáng):3397:77-04-06
有興趣的可以看看我花了3 天寫的代碼(重構(gòu)過一次應(yīng)該還是可以看看的 ) 下載:myGGUtil.rar包說明: ?本次 代碼在 myGGUtil.LGBeanUtil.LGUtil 下 (^_^)大家提點(diǎn)意見哦 ! 我希望這個(gè)好的想法 能成一個(gè)框架 哦~~~
?
BUG修訂 09-21 15:44
???時(shí)間類不能Update 問題 (如果在上面時(shí)間前下載那請(qǐng)從新下載)
?
在上一版本有大改動(dòng) 自用小框架:DB工廠?? ?????????1.? 添加 jdbc ?事物 ?????????2.? 結(jié)構(gòu)更合理 ???????? 3.? 速度加快
工具簡(jiǎn)單說明 ??????脫離 DB 影射包 java 數(shù)據(jù)類 ,動(dòng)態(tài)在內(nèi)存中生成 動(dòng)態(tài)數(shù)據(jù)類 ( 使用BeanUtils的DyanBean類?)??????. ????? 操作DB 面向?qū)ο蟛僮?當(dāng)然是動(dòng)態(tài)^_^) ????? 為了更實(shí)用 我用了張 50多屬性的大表進(jìn)行測(cè)試.閱讀起來可能有點(diǎn)困難,希望大家海涵.? version? ???jdk 1.4
下載 ??????DyanDBUtils.rar
包文件說明 : ?????????Config ? :? JDBC 需要的 驅(qū)動(dòng) 密碼等 ???????? DBResources :?? 根據(jù)Config給出 Connection ,? PreparedStatement ?????????DynaClass :? 根據(jù)元數(shù)據(jù) 和 table 給出 動(dòng)態(tài)BasicDynaClass? ?????????SQLSpelling : 給出 sql 語句和 sql語句中 ? ?的值?,格式為 List?:?lise.get(0)為sql語句 后其他為值?? ?????????DyanDBUtils.java : 為本Util主要入口點(diǎn) 也是運(yùn)行點(diǎn)
數(shù)據(jù)庫表? z_jcyy_basepersonnel ??????有53個(gè)屬性?(什么類型都有) ??????4 個(gè)不為空屬性 personid , workno , depotid ,? hname?????
測(cè)試
package
?DyanDBUtils.test;
import
?java.util.Iterator;
import
?org.apache.commons.beanutils.BeanUtils;
import
?DyanDBUtils.DyanDBUtils;
import
?junit.framework.TestCase;
public
?
class
?testUtil?
extends
?TestCase?{ ????
static
?
private
?DyanDBUtils?dyd?
=
??DyanDBUtils.getDyanDBUtil()?; ????
static
?
private
?Object?obj?
=
?
null
?; ????//SELECT ????
public
?
void
?testSelete()
throws
?Exception{ ????????dyd.setIsShowSQL(
true
); ????????
for
(Iterator?it?
=
?dyd.select(
"
select?t.*,?t.rowid?from?z_jcyy_basepersonnel?t?where?t.personid?=?'0301003719'
"
).iterator(); ????????????????????it.hasNext();){ ????????????Object?obj?
=
?it.next();
????????} ????} ????//INSERT ????
public
?
void
?testInsert()
throws
?Exception{ ????????obj?
=
?dyd.getDyanDBBean(
"
z_jcyy_basepersonnel
"
); ????????????BeanUtils.setProperty(obj,
"
personid
"
,
"
1000
"
); ????????????BeanUtils.setProperty(obj,
"
workno
"
,
"
2000
"
); ????????????BeanUtils.setProperty(obj,
"
depotid
"
,
"
300
"
); ????????????BeanUtils.setProperty(obj,
"
hname
"
,
"
劉凱毅
"
); ????????dyd.insert(obj);?? //INSERT?
????}
???//UPDATE ????
public
?
void
?testUpdate()
throws
?Exception{ ????????BeanUtils.setProperty(obj,
"
hname
"
,
"
思考..
"
); ????????dyd.updateOrInsert(obj); //UPDATE
????} //DELECT ????
public
?
void
?testDelete()
throws
?Exception{ ????????dyd.delete(obj);//DELECT
????????System.out.println(
"
******************************************
"
); ????} ???? ????
public
?
void
?testCommit()
throws
?Exception{ ????????dyd.openCommit()?; ????????Object?obj?
=
?dyd.select(
"
select?t.*,?t.rowid?from?z_jcyy_basepersonnel?t?where?t.personid?='0301003719'?
"
).get(
0
); ???????? ????????BeanUtils.setProperty(obj,
"
hname
"
,
"
劉凱毅
"
); ????????dyd.updateOrInsert(obj);
????????BeanUtils.setProperty(obj,
"
workno
"
,
null
);?
//
不可為空
????????dyd.updateOrInsert(obj); ???????? ????????dyd.colseCommit(); ????????testSelete(); ????} ???? }
測(cè)試測(cè)試結(jié)果 (注意: 開頭的 李家佳?3719? 和后面的 3719? 沒變 就是事物的結(jié)果)
李家佳?
3719
insert
?
into
?z_jcyy_basepersonnel(?depotid,drivekm,hname,hundreds,personid,resbaseknowledge,rescheck,resctrl,resproknowledge,ressaferules,roomarea,safekm,status,workno)?
values
(??,?,?,?,?,?,?,?,?,?,?,?,?,?)
//劉凱毅?2000?? print insert
//
思考..?
2000???? print update
delete
?
from
?z_jcyy_basepersonnel?
where
?
1
=
1
??
and
?personid
=
?
******************************************
delete
?
from
?z_jcyy_basepersonnel?
where
?
1
=
1
??
and
?personid
=
?
insert
?
into
?z_jcyy_basepersonnel(?beginworktime,depotid,deptid,dob,drivekm,drivelocotype,dynamicinfo,dynamicinfo2,dynamicinfo3,eductionlevel,folk,hname,hundreds,marrystatus,minordriveno,nativeplace,personid,political,postid,promoteminordriverdate,resbaseknowledge,rescheck,resctrl,resproknowledge,ressaferules,roomarea,safebeginday,safekm,sex,status,techniclevel,workno)?
values
(??,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
delete
?
from
?z_jcyy_basepersonnel?
where
?
1
=
1
??
and
?personid
=
?
insert
?
into
?z_jcyy_basepersonnel(?beginworktime,depotid,deptid,dob,drivekm,drivelocotype,dynamicinfo,dynamicinfo2,dynamicinfo3,eductionlevel,folk,hname,hundreds,marrystatus,minordriveno,nativeplace,personid,political,postid,promoteminordriverdate,resbaseknowledge,rescheck,resctrl,resproknowledge,ressaferules,roomarea,safebeginday,safekm,sex,status,techniclevel)?
values
(??,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) java.sql.SQLException:?ORA
-
01400
:?無法將?
NULL
?插入?("JCYY"."Z_JCYY_BASEPERSONNEL"."WORKNO") //事物運(yùn)行良好 哦
李家佳?3719
總結(jié) 事物 解決了 還有多表問題 大家多給點(diǎn)鼓勵(lì)哦 ^_^?
BUG 修改 :
09-20?? 因?yàn)? Oracle??取元數(shù)據(jù)的字符串需要 大寫 至修改并下載更新 測(cè)試使用表 ??????ID?????????????????????????? SN?? STATIONNAME????????? SPELL????? DEPOTID? ??????-------------- ---- -------------------- ---------- ------- ------------------ ??????08050000390689??? 3???? 永安???????????????????????????? ?ya??????????????? ....版本升級(jí) 09-21 DyanDBUtils 動(dòng)態(tài)面向?qū)ο髷?shù)據(jù)庫 操作由于 hibernate 還要table影射成class 這好處和壞處只有我們程序員知道了 ??????? 只要修改數(shù)據(jù)庫就大量影射附加工作要做 ,有時(shí)影射還有BUG弄的我們@#$%!.....(哈hibernate我是小鳥^_^),我----不要----影射 , 沒有他們數(shù)據(jù)庫就又回到j(luò)dbc.本人比較喜歡偷懶 哈哈 自己來個(gè)小框架吧( 就300來行的代碼有興趣的看看哦 )!!!? 用到技術(shù) ???? BeanUtil , JDBC元數(shù)據(jù)(在這我可是好好看了下JDBC,其實(shí)他是很強(qiáng)的東西,大家應(yīng)該好好用用^_^)? 下載 DBFactory.rarDBFactroy 數(shù)據(jù)是:+----+-------+-------------+------------+ | id | title | description | buydate??? | +----+-------+-------------+------------+ |? 6 | tt??? | asdgwgw???? | 1990-12-02 | +----+-------+-------------+------------+先看看測(cè)試吧
public?class?testNotKonw?extends?TestCase?{
????protected?void?setUp()?throws?Exception?{ ?????? //運(yùn)行 sql 可見 ????????DBFactory.getTools().setIsShowSql(DBFactory.SHOW); ????????super.setUp(); ????} ????public?void?testDelete()throws?Exception{ ?????????// select 出來 就的 List 中 DynaBean?: id , title?.....? 類型 , 和值都有了 ????????for(Iterator?it?=?DBFactory.getTools().select("select?*?from?books").iterator();it.hasNext();){ ????????????// 那就是delete :?目的是測(cè)試前 刪除全部數(shù)據(jù) ????????????DBFactory.getTools().delete(it.next()); ????????} ????} ???? ??????public?void?testInsert()throws?Exception{ ??????? // insert 要先new出來個(gè) table->bean??再?添屬性 ? ????????Object?obj?=?DBFactory.getTools().getDynaTableClass("books").newInstance(); ????????BeanUtils.setProperty(obj,"id","6"); ????????BeanUtils.setProperty(obj,"title","tt"); ????????BeanUtils.setProperty(obj,"description","asdgwgw"); ????????BeanUtils.setProperty(obj,"buydate",new?Date()); ?????? //這幾是 insert 了 (簡(jiǎn)單吧) ????????DBFactory.getTools().insert(obj); ????} ???? ????//?update ????public?void?testUpdate()throws?Exception{ ????????for(Iterator?it?=?DBFactory.getTools().select("select?*?from?books").iterator();it.hasNext();){ ????????????Object?obj?=?it.next(); ????????????BeanUtils.setProperty(obj,"buydate",new?Date(90,11,2)); ????????????DBFactory.getTools().update(obj); ????????} ????} }
控制臺(tái)輸出 //testDelete delete from books where 1=1? and id=6 //testInsert insert into books(id,title,description,buydate) values( 6,'tt','asdgwgw','2007-09-19') //testUpdate delete from books where 1=1? and id=6 insert into books(id,title,description,buydate) values( 6,'tt','asdgwgw','1990-12-02')
代碼關(guān)鍵說明: 關(guān)鍵在BeanUtil 的 DnayBean中 我通過元數(shù)據(jù) 得到了 這個(gè)Bean 屬性.屬性類型,還有表信息放在 getClass();的字符串中 ???EG:????table=...;key=..,..,..;columns=...,..,;?后在insert ,?delet , update就是(先delete后insert^_^) ?中?解析得到 動(dòng)態(tài)寫sql語句? ?????????更舉 DnayBean中屬性類型看看 Bean value 是否要加 ' value?' 還是直接 value 到sql 中
????public??BasicDynaClass?getDynaTableClass(String?table){ ????????Connection?conn?=?getConn()?; ????????List?props?=?new?ArrayList(); ????????DatabaseMetaData?dm?=?null?; ????????BasicDynaClass?dynaClass?=?null?; ????????try?{???? ????????????dm?=?conn.getMetaData(); ????????????ResultSet?coulumns?=?dm.getColumns(null,null,table,null); ????????????while(coulumns.next()){ ?????????????? //元數(shù)據(jù)中得到 類型做?DynaBean 屬性?? coulumns.getInt("DATA_TYPE")? 是? java.sql.Types.XXXXX ????????????????props.add(new?DynaProperty(?coulumns.getString("COLUMN_NAME"),getStrClass(coulumns.getInt("DATA_TYPE")))?); ????????????} ????????????//?all?:?table ????????????//delete?:?column_name?column_value ????????????//insert?:?column_name ????????????StringBuffer?sb?=?new?StringBuffer(); ????????????sb.append("table=").append(table).append(";"); ???????????? ????????????sb.append("keys="); ????????????????ResultSet?keys?=?dm.getPrimaryKeys(null,null,table); ????????????????while(keys.next()){ ????????????????????sb.append(?keys.getString("column_name")).append(","); ????????????????} ????????????????sb.replace(sb.length()-1,sb.length(),";"); ???????????? ????????????sb.append("columns=");???? ????????????????ResultSet?couls?=?dm.getColumns(null,null,table,null); ????????????????while(couls.next()){ ????????????????????sb.append(?couls.getString("column_name")).append(","); ????????????????} ????????????????sb.replace(sb.length()-1,sb.length(),";"); ???????????????? ??????????? //為 Class name? <- sb.toString() ????????????dynaClass?=?new?BasicDynaClass(sb.toString()?,?null,? ????????????????????(DynaProperty[])props.toArray(new?DynaProperty[]{})?); ????????}?catch?(Exception?e)?{e.printStackTrace();} ????????finally{ ????????????try?{ ????????????????conn.close()?; ????????????}?catch?(SQLException?e)?{e.printStackTrace();} ????????} ????????return?dynaClass?; ????} insert , delete 差不多 就來insert
????public?boolean?insert(Object?obj){ ????????String?sqlstrat?=?"insert?into?"; ????????String?sqldo?=?"?values(?"; ????????String?sqlend?=?")"; ????????String?sql?=?""; ????????boolean?od?=?false?; ???????? ????????Connection?conn?=?getConn()?; ????????Statement?sta?=?null?; ????????try?{ ???????????? //解析getDynaClass().getName()? 得到 table ????????????sqlstrat?+=?getTableConfig(obj,"table")[0]+"("?; ???????????? ???????????? //解析getDynaClass().getName()? 得到?columns ????????????String[]?cols?=?getTableConfig(obj,"columns"); ????????????for(int?i=0;i<cols.length;i++){ ????????????????sqlstrat?+=?cols[i]??+","; ????????????????sqldo?+=?getSqlAtt(obj,cols[i]?)+","; ????????????} ????????????sql?=?sqlstrat.substring(0,sqlstrat.length()-1)+")"+sqldo.substring(0,sqldo.length()-1)+sqlend; ????????????sta?=?conn.createStatement(); ????????????if(?sta.executeUpdate(sql)>0){od?=?true;}; ????????}?catch?(Exception?e)?{e.printStackTrace();} ????????finally{ ????????????try?{ ????????????????if(?isShowSql==SHOW?)?{System.out.println();System.out.println(sql);} ????????????????conn.close(); ????????????}?catch?(SQLException?e)?{e.printStackTrace();} ????????} ????????return?od?; ????}
小結(jié): 當(dāng)然表連和多表 查 是沒問題的 但在多表 delete , update 就還沒有完成 (蠻難的 5555? 還有 沒時(shí)間) 單表的 delete update ,select,insert 都完成了 我會(huì)努力的 大家要是認(rèn)為還可以 幫忙頂貼 哦 我會(huì)都都完善哦
本人特留使用 ( ^_^ 寫html 不多 呵呵 ) ??? 本頁問題說明: 在第一次加載這3個(gè)頁面的javascript可正常使用 ?????????????????? 后 ajax修改的( innerHTML= )頁面 javascript就使用不了全頁的document而是修改后的document ??? ?? ?? ?? ?? ?? 有人可以幫幫忙嗎? <%@?page?language="java"?import="java.util.*"?pageEncoding="GBK"%> <% String?path?=?request.getContextPath(); String?basePath?=?request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %>
<!DOCTYPE?HTML?PUBLIC?"-//W3C//DTD?HTML?4.01?Transitional//EN"> <html> ??<head> ????<base?href="<%=basePath%>"> ???? ????<title>My?JSP?'Layout.jsp'?starting?page</title> ????? ????<meta?http-equiv="pragma"?content="no-cache"> ????<meta?http-equiv="cache-control"?content="no-cache"> ????<meta?http-equiv="expires"?content="0"> ????<meta?http-equiv="keywords"?content="keyword1,keyword2,keyword3"> ????<meta?http-equiv="description"?content="This?is?my?page"> ????<SCRIPT?src="http://127.0.0.1:7000/jspLayout/js/ajax.js"></SCRIPT> ????<!-- ????<link?rel="stylesheet"?type="text/css"?href="styles.css"> ????--> ??</head> ?? ??<body> ???????????<%@include?file="../html/top.jsp"%> ???????????<table?width="90%"> ???????????????<tr> ???????????????????<td??valign="top"?align="center"?height="80%"> ???????????????????????<jsp:include?flush="true"??page="../html/left.html"/> ???????????????????</td> ???????????????????<td?id="cen"?valign="middle"?align="center"?width="80%"?height="80%"> ???????????????????????<jsp:include?flush="true"??page="../html/center.html"/> ???????????????????</td> ???????????????</tr> ???????????</table> ??</body> </html>
使用后好處? ??? java 和 javascript 使用同統(tǒng)一對(duì)象,語法?. 數(shù)據(jù)從 sever 到 v層?和?v層 到 sever ?方便. ??????????? 簡(jiǎn)單說就是?JBean 不做修改拿到V層 當(dāng) JSBean (javascript 類)?中用
1.url 亂碼問題參照 Ajax uri 亂碼問題總結(jié)(IE,FF) 2.使用jar是 jxpath ; json? ......(與相關(guān)) ???????????????jxpath 參照 jxpath 學(xué)習(xí)筆記? ???????????????json 參照 使用json-lib
例題說明 數(shù)據(jù) name,avg 在通過 ajax json 后 avg +1 再展現(xiàn)到頁面 本頁需要 json.js 下載到 http://www.json.org/json.js?
<%
@?page?pageEncoding
=
"
GBK
"
%>
<%
@?page?contentType
=
"
text/html;?charset=GBK
"
?
%>
??
<
html
>
??
<
head
>
????
<
title
>
json.html
</
title
>
???? ????
<
meta?
http-equiv
="keywords"
?content
="keyword1,keyword2,keyword3"
>
????
<
SCRIPT?
src
="../js/json.js"
?
></
SCRIPT
>
? ????
<
script?
language
="javascript"
?type
="text/javascript"
>
????
var
?request?
=
?
false
; ???? ?? // javascript ?Ajax? 沒什么好說的 這可以用 prototype prototype.js 的理解??,dojo?dojo? 等 ajax ? //本例?為方便直接寫了 ^_^? ????
function
?getOpen(){?????? ???????
try
?{ ?????????request?
=
?
new
?XMLHttpRequest(); ???????}?
catch
?(trymicrosoft)?{ ?????????
try
?{ ???????????request?
=
?
new
?ActiveXObject(
"
Msxml2.XMLHTTP
"
); ?????????}?
catch
?(othermicrosoft)?{ ???????????
try
?{ ?????????????request?
=
?
new
?ActiveXObject(
"
Microsoft.XMLHTTP
"
); ???????????}?
catch
?(failed)?{ ?????????????request?
=
?
false
; ???????????}?? ?????????} ???????} ????}??? ??????? ??????? ??????
function
?getCustomerInfo()?{ ??????getOpen(); ???????
if
?(
!
request) ?????????alert(
"
Error?initializing?XMLHttpRequest!
"
); ????????? ?????? //這通過 url 把數(shù)據(jù)傳給 server? ?????? //數(shù)據(jù)來源 javascript 類 就下方 DBdata???? string:?name:我名字^_^??,? int:?avg:年齡^_^ ?????????
var
?url?
=
?
"
/json/json?jsonStr=
"
+
?(
new
?DBdata()).toJSONString()?; ?????????request.open(
"
GET
"
,?url,?
true
); ?????????request.send(
null
); ?????????request.onreadystatechange?
=
?updatePage; ???????} ??????? ?????? //?ajax 處理?數(shù)據(jù)后返回的?結(jié)果? ????? // 年齡 +1?并輸入到 輸入框中 ???????
function
?updatePage(){ ???????
if
?(request.readyState?
==
?
4
)? ???????????
if
?(request.status?
==
?
200
){? ??????????? //得到 json str ?????????????
var
?jss?
=
?request.responseText; ??????????? //加載到 javascript 類中 string -> jsBean ?????????????
var
?jsobj?
=
?eval('('?
+
?jss?
+
?')'); ???????????? //使用和 java對(duì)象一樣 ^_^ ?????????????document.getElementById('xx').value?
=
?jsobj.name?
+
':'
+
?jsobj.avg?; ????????????} ???????} ???? //數(shù)據(jù)來源 ?????
function
?DBdata(){ ?????????
this
.name?
=
?'劉凱毅'; ?????????
this
.avg
=
23
;? ?????????
this
.init
=
function
(){ ?????????????alert('呵呵'); ?????????} ?????}
</
script
>
??
</
head
>
??
<
body?
onload
=""
>
??????
<
INPUT?
id
='xx'?
type
="text"
?
>
??????
<
INPUT?
id
='x'?
type
="button"
?onclick
="getCustomerInfo()"
?value
="go"
>
??
</
body
>
</
html
>
為了方便明了我java方就使用了 server package?servlet;
import?java.io.IOException; import?java.io.PrintWriter;
import?javax.servlet.ServletException; import?javax.servlet.http.HttpServlet; import?javax.servlet.http.HttpServletRequest; import?javax.servlet.http.HttpServletResponse;
import?org.apache.commons.jxpath.JXPathContext;
import?net.sf.json.JSONObject;
public?class?Json?extends?HttpServlet?{ ????public?void?doGet(HttpServletRequest?req,HttpServletResponse?rpo)throws?ServletException,IOException{ ????????rpo.setCharacterEncoding("GBK"); ????????req.setCharacterEncoding("GBK"); ????????rpo.setContentType("text/html;?charset=GBK"); ???????? ????????PrintWriter?out?=?rpo.getWriter()?; ??????? ??? ??? //得到 url 傳入數(shù)據(jù) ????????String?str?=?req.getParameter("jsonStr")?; ??? ??? //java 方 string -> javaBean ????????JSONObject?jso?=?JSONObject.fromString(str); ??? ??? //javaBean 使用jxpathcontxt解讀更方便 ^_^ ??????? //其實(shí)jso中是以 map 形式存區(qū)的 有興趣的可以自己動(dòng)手寫下哦 ????????JXPathContext?jx?=?JXPathContext.newContext(jso); ????????try?{ ??? ?? ?? ?? //jxpath好處來了 avg + 1 ????????????jx.setValue("./avg",?jx.getValue("./avg?+?1?")?); ????????}?catch?(Exception?e)?{e.printStackTrace();} ??? ??? ??? ?? //以 jsonString 傳出 ????????out.print(jso.toString());
????} }
web.xml(好象有點(diǎn)多嘴了 哈哈 方便下入門人了) ????<servlet> ????????<servlet-name>json</servlet-name> ????????<servlet-class>servlet.Json</servlet-class> ????</servlet> ????<servlet-mapping> ????????<servlet-name>json</servlet-name> ????????<url-pattern>/json</url-pattern> ????</servlet-mapping>
|