|
2007年6月13日
学习就从官方的测试开始,但不知道怎么回事官方的测试有问题,这我就把我配置的简单junit环境共享给大家把! 1.下载 hibernate-annotations-3.4.0.GA 并解压 ,cd 到解压后目录下 2. $> ant junit (天知道,怎么官方出的东西测试不能通过!!) 不要急,我们来看错误 (错误提示有删减) 错误-1:$>build.xml:95: ./jdbc not found. 解决办法-1: $>mkdir ./jdbc 3. $> ant junit 错误-2: ./build.xml:124: The following error occurred while executing this line: ./build.xml:126: The following error occurred while executing this line: ./common-build.xml:349: .\src\filters\hsqldb.filter as it doesn't exist. 解决办法-2: $> mkdir ./src/filters ; $> echo "" > ./src/filters/hsqldb.filter; 4. $>ant junit 错误-3: ./build.xml:124: The following error occurred while executing this line: ./build.xml:126: The following error occurred while executing this line: ./common-build.xml:351: .\src\test-resources not found. $> mkdir ./src/test-resources ; 5. $> ant junit 错误-4:没有ant 错误了!,但测试都为错误,那我们就看看 第一个测试吧,找下原因! test-resources: [mkdir] Created dir: hibernate-anntations-3.4.0.GA\build\test-reports\hsqldb [echo] Running against db: hsqldb [junit] Running org.hibernate.test.annotations.ConfigurationTest [junit] Tests run: 7, Failures: 0, Errors: 6, Time elapsed: 1.218 sec ............. $> find . -name "ConfigurationTest.java" #pwd /hibernate-anntations-3.4.0.GA ./test/org/hibernate/test/annotations/configuration/ConfigurationTest.java ./test/org/hibernate/test/annotations/ConfigurationTest.java 根据路径 org.hibernate.test.annotations.ConfigurationTest gvim ./test/org/hibernate/test/annotations/ConfigurationTest.java 发现第20行: cfg.configure( "org/hibernate/test/annotations/hibernate.cfg.xml" ); 感觉应该没有配置 jdbc gvim ./test/org/hibernate/test/annotations/hibernate.cfg.xml #果然 没配置 我这就放个我的简单配置上来(使用 hbm hsqldb 内存数据库测 试 ): <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="hibernate.dialect">org.hibernate.dialect.HSQLDialect</property> <property name="connection.driver_class">org.hsqldb.jdbcDriver</property> <property name="connection.url">jdbc:hsqldb:mem:hbn_ann</property> <property name="connection.username">sa</property> <property name="connection.password"></property> <mapping resource="org/hibernate/test/annotations/Boat.hbm.xml"/> <mapping package="org.hibernate.test.annotations"/> <mapping class="org.hibernate.test.annotations.Plane"/> </session-factory> </hibernate-configuration> 我这就是要hsqldb吧,既然上面错误1有 jdbc 文件夹,那就是放 jdbc jar 的地方 $> cp ../hsqldb.jar ./jdbc 6. $> ant junit 呵呵 测试 第一个正确了 ! (目前配置后,测试环境并不是全部都正确,比如第2个测试) 其他测试错误日志在 .\build\test-reports\hsqldb ... 比如第2个错误 异常部分 org.hibernate.HibernateException: The dialect was not set. Set the property hibernate.dialect. at org.hibernate.dialect.Dialect.instantiateDialect(Dialect.java:256) at org.hibernate.dialect.Dialect.getDialect(Dialect.java:234) ........ 大家一边学习,一边配置测试 环境吧。 错误日记 都会在 build\test-reports\hsqldb下
参考: http://tech.ddvip.com/2008-12/122835390597191.html 页面可以直接运行: <html> <head>
<style type="text/css">
.box1 { float:left; width:21px; height:21px; position:relative; background: #F3F2E2 url(http://mp3.youdao.com/images/mbox_bg.gif) no-repeat; } .box1 { background-position: 0px -60px; }
</style>
</head>
<body>
<div class="box1" onmouseover="this.style.backgroundPosition='0px -81px' " onmouseout="this.style.backgroundPosition='0px -102px' " > </div>
</body>
</html>
javascript 学习
javascript 大体上可分为3个不同部分组成: 核心(ECMAscript),文本对象(DOM),浏览器对象(BOM)
-
核心(ECMAscript): 关键字,语句,运算符,对象
-
文本对象(DOM):DOM将把整个页面规划成由节点层级构成的文档.
-
解析遵循 W3C html dom 标准:
-
W3C dom 参考特别关注 DOM Node 说明
-
BOM 浏览器对象. cookie,弹出新浏览器,浏览器设置大小
核心(ECMAscript)Global 内置对象;
方法: parseInt(),isNan(),encodeURI()...等都为此对象方法 特别注意 eval();动态语言的象征 比如:eval("alert('hi')"); 但这个方法很邪恶(安全方面)
文本对象(DOM)说明:
<bookstore> <book category="cooking"> <title lang="en">Everyday Italian</title> <author>Giada De Laurentiis</author> <year>2005</year> <price>30.00</price> </book> </bookstore> | | |
1. ECMAscript基础 $ 变量弱类型 ; 匈牙利类型标示 : var iOuouValue=100;
$ 结束行分号有无都可以; 但再 onsubmit="javascript:function();return false;" $ 关键字 ; 提别注意
"constructor" bean.constructor
//print bean function(){ ....
}
"typeof" var test=1; alert(typeof testX); //output "undefined" "NaN" - not a number -> isNan("blue"); //output "true" ->isNan("123"); //output "false" $ 对象; var o = new Object(); var a = {}
这里特别说明下 我们普通写的 一个 function 就是一个 object 这 var a = {name:"刘凯毅"} 等同与 var a = function(){this.name="刘凯毅"}; 来个 {name:"test",pass:"123456",addr:"bj"} //这是什么 ?! json
当 var str = '{name:"test",pass:"123456",addr:"bj"}' var objectBean = eval(str); //这里就是 对象 objectBea.name 使用了
域概念: <SCRIPT type=text/javascript>
var sMessage = 'Hello';
function setSomething() {
sColor = 'red';
sMessage = 'Hello World!';
}
setSomething();
alert(sMessage); //Hello World!
alert(sColor); //red
</SCRIPT> | <SCRIPT type=text/javascript>
var sMessage = 'Hello';
function setSomething() {
var sColor = 'red';
sMessage = 'Hello World!';
}
setSomething();
alert(sMessage); //Hello World!
alert(sColor); // 什么都没有
</SCRIPT>
| <SCRIPT type=text/javascript>
var sMessage = 'Hello';
function setSomething() {
var sColor = 'red';
var sMessage = 'Hello World!';
}
setSomething();
alert(sMessage); //Hello
alert(sColor); // 什么都没有
</SCRIPT>
|
为面向对象做基础:object prototype 类型的对象应用。参考 // 最简单的 继承
Object.prototype.inObj = 1;
function A()
{
this.inA = 2;
}
A.prototype.inAProto = 3;
B.prototype = new A; // Hook up A into B's prototype chain
B.prototype.constructor = B;
function B()
{
this.inB = 4;
}
B.prototype.inBProto = 5;
x = new B;
document.write(x.inObj + ', ' + x.inA + ', ' + x.inAProto + ', ' + x.inB + ', ' + x.inBProto);
//1, 2, 3, 4, 5
//增加点信心 http://www.json.org/json.js
Object.prototype.toJSONString = function (filter) { return JSON.stringify(this, filter); }; 后我们就可以使用 bean.toJSONString()不是吗?
|
$ arguments ; function getFun(){alert(arguments.length);} ;
getFun("xx") //output 1 getFun("xx",23) //output 2
$ 语句 ;特殊说明下 for for(var i=0i<iCount;i++) 或 for( attr in object ) ;
如果无聊 你可以 for( sProp in window ){alert(sProp+"你丫点啊!");} //看看 javascript 的反射
面向对象: var bean = new Bean();
1.工厂方法 function getAttr(){ alert(this.attr)
} function Bean(tattr){ var bean = new Object; bean.attr = tattr; bean.getAttr = getAttr; return bean ;
} 根本就是山寨版 面向对象
2.构造 function Bean(tattr){ this.attr = tattr ; bean.getAttr = function(){ alert(this.attr); } } 其上 2 总 再Bean 对象创建时,方法会 “重复生成函数”!
3.原型模式 function Bean(){} Bean.prototype.attr = ""; Bean.prototype.getAttr=function(){alert(this.attr);}
解决 “重复生成函数” 问题,但新的问题 Bean.prototype.getArray = new Array();
其 new 对象 bean1 和 bean2 都会共享 new Array 空间(是我们不想看到的)
4.混合 模型 :) 哈哈 function Bean(){ this.attr= "";
this.getArray=new Array;
} Bean.prototype.getAttr=function(){alert(this.attr);}
5.动态原型 (注意下面开始,就是真正的面向对象!!!) function Bean(){ this.attr= "";
this.getArray=new Array; //classload 加载 时
if(typeof Bean._initialized == "undefined" ){ Bean.prototype.getAttr=function(){alert(this.attr);};
Bean._initialized= true ; }
}
/****************************************************************/
对象继承
1.对象冒充!!(可支持多继承,山寨很强大)
function classA(sstr){ this.color = sstr ; this.sayColor = function(){ alert(this.color);
};
} function classC(){}
function classB(){ this.newMethod =ClassA ; this.newMethod(); delete this.newMethod ;
this.newMethod =ClassC ; this.newMethod(); delete this.newMethod ; this.arrt = "google";
}
2.call() apply() 也山寨, function classA(sstr){ this.color = sstr ; this.sayColor = function(str){ alert(str+this.color);
};
}
function classB(){ // this.newMethod =ClassA ; // this.newMethod(); // delete this.newMethod ; classA.call(this,"red"); //classA.apply(this,new Array("red"))
this.arrt = "baidu";
} 3.正统的继承 原型链 (但不支持多继承) function classA(){this.oo="test";} classA.prototype.color = "red"; function classB(){} classB.prototype = new classA ; classB.prototype.sayName = function(){ alert( this.color ); } var bb = new classB ; bb.sayName(); // output red alert(bb.oo); // output test
alert( bb instanceof classA); //output true alert( bb instanceof classB); //output true4.如果你要多继承!!并且还支持 instanceof 混合方式: function classA(){} function classB(){} function classC(){ classA.call(this); classC.call(this); } classC.prototype = new classA ;//注意 这 instanceof 只能对 A有用
下载:flash-plugin-10.0.15.3-release.i386.rpm
rpm -ivh flash-plugin-10.0.15.3-release.i386.rpm
tomcat > server.xml
<Host name="localhost" appBase="webapps" unpackWARs="true" autoDeploy="true" xmlValidation="false" xmlNamespaceAware="false">
<Context docBase="D:/workspace/meganotes/mn_mod_admin/target/mn_mod_admin/" path="/" />
。。。。
关键:在Context上不要加reloadable和debug属性 然后 使用eclipse tomcat 调试 ok
<?
xml version="1.0" encoding="UTF-8"
?>
<
project
name
="ssh"
>
<
property
file
="ssh.properties"
/>
<
tstamp
>
<
format
property
="TODAY"
pattern
="yyyyMMddHHmm"
/>
</
tstamp
>
<
property
name
="ssh.path"
value
="/data/meganotes/shell/"
/>
<
target
name
="shell/ 文件 上载/覆盖"
>
<
input
addproperty
="scp_coverage_shell_file"
message
="输入(ssh/ 下文件名 \n\r 上载或覆盖 到服务器 218 ${ssh.path} ):"
>
</
input
>
<
input
message
="请确定是否使用 ssh/${scp_coverage_shell_file} 覆盖服务器中 ${ssh.host}:${ssh.path}${scp_coverage_shell_file} (y,n)"
validargs
="y,n"
addproperty
="do.coverage"
defaultvalue
="n"
/>
<
condition
property
="do.abort"
>
<
equals
arg1
="n"
arg2
="${do.coverage}"
/>
</
condition
>
<
fail
if
="do.abort"
>
退出
</
fail
>
<
sshexec
host
="${ssh.host}"
username
="${ssh.myName}"
password
="${ssh.myPass}"
trust
="true"
command
=" mkdir -p ${ssh.path}backup/${TODAY} ; if [ -f ${ssh.path}${scp_coverage_shell_file} ] ; then cp ${ssh.path}${scp_coverage_shell_file} ${ssh.path}backup/${TODAY}/ ; fi ; "
>
</
sshexec
>
<
scp
file
="ssh/${scp_coverage_shell_file}"
todir
="${ssh.myName}:${ssh.myPass}@${ssh.host}:${ssh.path}"
trust
="true"
verbose
="true"
/>
<
sshexec
host
="${ssh.host}"
username
="${ssh.myName}"
password
="${ssh.myPass}"
trust
="true"
command
="chmod 777 ${ssh.path}${scp_coverage_shell_file}"
>
</
sshexec
>
</
target
>
<
target
name
="shell/ 文件查看"
>
<
input
addproperty
="show_shell_file"
message
="输入查看文件名(*sh):"
defaultvalue
="*"
>
</
input
>
<
sshexec
host
="${ssh.host}"
username
="${ssh.myName}"
password
="${ssh.myPass}"
trust
="true"
command
="ls /data/meganotes/shell/${show_shell_file}"
>
</
sshexec
>
</
target
>
<
target
name
="shell/ 文件拷贝"
>
<
input
addproperty
="scp_shell_file"
message
="输入 /data/meganotes/shell/ 下需要文件名(cp 到 ssh 下):"
>
</
input
>
<
scp
file
="${ssh.myName}:${ssh.myPass}@${ssh.host}:/data/meganotes/shell/${scp_shell_file}"
todir
="ssh"
trust
="true"
verbose
="true"
/>
</
target
>
<
target
name
="admin-mvn组合操作"
>
<
exec
executable
="cmd"
>
<
arg
value
="/c"
/>
<
arg
value
="${basedir}/sh/mvn/meganotes_mvn_clear.bat"
/>
</
exec
>
<
exec
executable
="cmd"
>
<
arg
value
="/c"
/>
<
arg
value
="${basedir}/sh/mvn/meganotes_mvn_install.bat"
/>
</
exec
>
<
exec
executable
="cmd"
>
<
arg
value
="/c"
/>
<
arg
value
="${basedir}/sh/mvn/mn_mod_admin_mvn_intall.bat"
/>
</
exec
>
</
target
>
<
target
name
="admin-tomcat日志"
>
<
sshexec
host
="${ssh.host}"
username
="${ssh.myName}"
password
="${ssh.myPass}"
trust
="true"
command
="${ssh.adminRunLog}"
>
</
sshexec
>
</
target
>
<
target
name
="schedule-tomcat日志"
>
<
sshexec
host
="${ssh.host}"
username
="${ssh.myName}"
password
="${ssh.myPass}"
trust
="true"
command
="${ssh.scheduleRunLog}"
>
</
sshexec
>
</
target
>
<
target
name
="查找2008/下Mp3没转128-64文件夹"
>
<
sshexec
host
="${ssh.host}"
username
="${ssh.myName}"
password
="${ssh.myPass}"
trust
="true"
command
="${ssh.64k}"
>
</
sshexec
>
<
sshexec
host
="${ssh.host}"
username
="${ssh.myName}"
password
="${ssh.myPass}"
trust
="true"
command
="${ssh.128k}"
>
</
sshexec
>
<
sshexec
host
="${ssh.host}"
username
="${ssh.myName}"
password
="${ssh.myPass}"
trust
="true"
command
="${ssh.128kto64k.err}"
>
</
sshexec
>
</
target
>
<
target
name
="admin模块测试"
>
<
input
addproperty
="admin_test_input"
message
="测试类输入(Video*Test):"
defaultvalue
="*Test"
>
</
input
>
<
echo
message
="${admin_test_input}"
></
echo
>
<
exec
executable
="cmd"
>
<
arg
value
="/c"
/>
<
arg
value
="${basedir}/sh/admin_test.bat ${admin_test_input} "
/>
</
exec
>
</
target
>
</
project
>
public
static
void
main(String[] args)
{
try
{ String charset
=
"
UTF-8
"
; String outfile
=
"
d:\\category.20081218.gz
"
; BufferedReader in
=
new
BufferedReader(
new
InputStreamReader(
new
FileInputStream(
"
d:\\category.20081218
"
), charset)); BufferedOutputStream out
=
new
BufferedOutputStream(
new
GZIPOutputStream(
new
FileOutputStream(outfile))); System.out.println(
"
Writing file
"
); String c;
while
((c
=
in.readLine())
!=
null
) out.write( (c
+
"
\n
"
).getBytes(charset)); in.close(); out.close(); System.out.println(
"
Reading file
"
); BufferedReader in2
=
new
BufferedReader(
new
InputStreamReader(
new
GZIPInputStream(
new
FileInputStream(outfile) ),charset ) ); String s;
while
((s
=
in2.readLine())
!=
null
) System.out.println(s); }
catch
(Exception e)
{ e.printStackTrace(); }
}
官方上下 http://bassistance.de/jquery-plugins/jquery-plugin-autocomplete/ $.补全中文 修改 jquery.autocomplete.js 中 $input.bind(($.browser.opera ? "keypress" : "keydown") 改为 $input.bind(($.browser.opera ? "keypress" : " keyup") $. 在 localdata.js 》》 var cities = [.. 中放些 中文 测试吧 测试页面 ,最简单的使用页面 。(应该算是最简单补全测试了) <script type="text/javascript" src="../lib/jquery.js"></script> <script type='text/javascript' src='../jquery.autocomplete.js'></script>
<link rel="stylesheet" type="text/css" href="../jquery.autocomplete.css" /> <script type="text/javascript"> $().ready(function() { $("#suggest1").autocomplete([ "test1", "test2", "测试1", "测试2" ]); }); </script>
<input type="text" id="suggest1" />
使用json <script type="text/javascript" src="../lib/jquery.js"></script> <script type='text/javascript' src='../jquery.autocomplete.js'></script>
<script type='text/javascript' src='localdata.js'></script> <link rel="stylesheet" type="text/css" href="../jquery.autocomplete.css" /> <script type="text/javascript"> var emails = [ { name: "Peter Pan", to: "peter@pan.de" }, { name: "Molly", to: "molly@yahoo.com" }, { name: "Forneria Marconi", to: "live@japan.jp" }, { name: "Master <em>Sync</em>", to: "205bw@samsung.com" }, { name: "Dr. <strong>Tech</strong> de Log", to: "g15@logitech.com" }, { name: "Don Corleone", to: "don@vegas.com" }, { name: "Mc Chick", to: "info@donalds.org" }, { name: "Donnie Darko", to: "dd@timeshift.info" }, { name: "Quake The Net", to: "webmaster@quakenet.org" }, { name: "Dr. Write", to: "write@writable.com" } ]
$().ready(function() { $("#suggest13").autocomplete(emails, { //补全中选择显示 formatItem: function(row, i, max) { return i + "/" + max + ": \"" + row.name + "\" [" + row.to + "]"; }, //补全匹配格式 formatMatch: function(row, i, max) { return row.name ; }, //补全选定后显示 formatResult: function(row) { return row.to; } }) }); </script>
不要为 拼写 ajax url 而郁闷了。希望能对大家有帮助。 /* 1.form ajax 使用: eG: form就是普通的 html form <input type="button" value="xx" onclick="formAjax('data.jsp',this.form,ajaxReturn)"/> function ajaxReturn(data){ document.getElementById("div1").innerHTML = data ; } 2.ajax 使用 : AjaxFunction AjaxFunction('url?param=tt¶m2=te',function(text){ alert(text); });
3.迭代器: recursiveNodes(array,dom,pushFun,layer) array 迭代寄存器 dom 被迭代对象 pushFun 自定义收集方法 pushFun(array,node,layer) node 迭代中对象 layer 深度 EG: var arr = [] ; recursiveNodes(arr ,dom,function(array,node,layer){ arr.push(node); },2);
*/ var _request; try { this._request = new XMLHttpRequest(); } catch (e) { try { this._request = new ActiveXObject('Msxml2.XMLHTTP'); } catch (e) { try { this._request = new ActiveXObject('Microsoft.XMLHTTP'); } catch (e) { request = false; } } }
var AjaxFunction = function(urls, getAjaxText) { AjaxFunction._getAjaxText = null;
_url = ''; _params = '';
AjaxFunction._getAjaxText = getAjaxText; var strs = urls.split(/\?/); _url = strs[0]; if (strs.length > 1) _params = strs[1];
_request.open("POST", this._url, true); _request.setRequestHeader("Cache-Control", "no-cache"); _request.setRequestHeader("content-type", "application/x-www-form-urlencoded"); _request.send(_params); _request.onreadystatechange = _onComplete; }; function _onComplete() { if (_request.readyState == 4) { if (_request.status == 200 || _request.status == 0) { if (_request.responseText != null && _request.responseText != '' && _request.responseText != ' ') AjaxFunction._getAjaxText(_request.responseText); } } }
/* * 迭代 1. array,dom 2. array,dom,layer */ function recursiveNodes(array, dom, pushFun, layer) { if (layer == 0) return; if (layer > 0) { --layer; if (dom.hasChildNodes && dom.hasChildNodes()) { for ( var i = 0; i < dom.childNodes.length; i++) { var nodeT = dom.childNodes.item(i); if (typeof pushFun == "function") pushFun(array,nodeT, layer); else array.push(nodeT); recursiveNodes(array, dom.childNodes.item(i), pushFun, layer); } } else return; } else if (layer < 0) { ++layer; var nodeT = dom.parentNode; if (nodeT) { if (typeof pushFun == "function") { pushFun(array,nodeT, layer); } else { array.push(nodeT); } recursiveNodes(array, dom.parentNode, pushFun, layer) } else return; } }
function formAjax(url,ttform,returnFun){ var datas = []; var arr = ['input','select']; recursiveNodes(datas,ttform,function(array,node,layer){ for(var i=0;i<arr.length;i++){ if( node.getAttribute ){ var paramName = node.getAttribute('name') ; if( /select/i.test( node.nodeName ) ){ array.push(paramName+'='+node.options[node.selectedIndex].value); }else if( paramName !=null && /^\s*(\w+)\s*$/g.test(paramName) && new RegExp(arr[i],'i').test(node.nodeName) ){ array.push(paramName+'='+node.value); } } } },999); //? ? //& & var urls = url+'?'+datas.join("&"); AjaxFunction(urls,returnFun); }
function trim(str){ return str.replace(/(^\s*)|(\s*$)/g,""); }
function recursiveNodes(array,dom,layer){ if( layer==0 ) return ; if(layer>0){ --layer; if( dom.hasChildNodes && dom.hasChildNodes() ){ for(var i=0;i<dom.childNodes.length;i++ ){ array.push(dom.childNodes.item(i)); recursiveNodes(array, dom.childNodes.item(i),layer ) ; } }else return ; }else if(layer<0){ ++layer; if( dom.parentNode ){ array.push( dom.parentNode ); recursiveNodes( array,dom.parentNode,layer) }else return ; } }
/* [@name || && > < >= <= != @location='UK'] */ function singleStep(dom,stepAction,stepStr){ var allArrData = [] ; var arrData = [] ; var num = stepAction.split(/\//).length ; recursiveNodes(allArrData,dom,num==2?1:999); stepStr = trim(stepStr) ; var nodeName ; var nodeNum ; var conds = true ; //判断单匹配 是否有 属性对比 [@..=..] if( /\[(.*?)\]/.test(stepStr) ){ nodeName = trim( /.*?(?=\[{1})/g.exec(stepStr)[0] ).replace(/\*/g,".*") ; conds = /\[(.*?)\]/.exec(stepStr)[1].replace(/\*/g,".*") ; if(! isNaN(conds) ){ nodeNum = parseInt(conds)-1;
}else{ //属性 替换为 conds = conds.replace(/(@)(.*?)(?=\W)/g," allArrData[i].getAttribute('$2') ") ; conds = conds.replace( /([\W]+)(.*?)::\'(.*?)\'/g," $1 /$3/g.test($2) " ) ; conds = conds.replace( /(text\(\))/g ," allArrData[i].innerHTML ") ; conds = conds.replace( /([\w\s])(=)/g ,"$2=") ;
} }else{ nodeName = stepStr ; }
for(var j=i=0;i<allArrData.length;i++){ if( eval('/'+nodeName+'/i.test( allArrData[i].nodeName ) ') ){ if(typeof nodeNum=="number"){ if(j==nodeNum){ arrData.push( allArrData[i] ); return arrData; } else ++j; }else if( eval(' allArrData[i].getAttribute && '+conds) ){ arrData.push( allArrData[i] ); } } } return arrData ; }
function getXpath(dom,xpathStr){ var xpaths = xpathStr.split(/(\/{1,2})/g); var arrDom = [dom] ; for(var i=1;i<xpaths.length;i=i+2){ var arrData = []; for(var j=0;j<arrDom.length;j++) arrData = arrData.concat( singleStep(arrDom[j],xpaths[i],xpaths[i+1]) ); arrDom = arrData ; } return arrDom ; }
****************************************************************************************************** function trim(str){ return str.replace(/(^\s*)|(\s*$)/g,""); }
function recursiveNodes(array,dom,layer){ if( layer==0 ) return ; if(layer>0){ --layer; if( dom.hasChildNodes && dom.hasChildNodes() ){ for(var i=0;i<dom.childNodes.length;i++ ){ array.push(dom.childNodes.item(i)); recursiveNodes(array, dom.childNodes.item(i),layer ) ; } }else return ; }else if(layer<0){ ++layer; if( dom.parentNode ){ array.push( dom.parentNode ); recursiveNodes( array,dom.parentNode,layer) }else return ; }
}
/* [@name || && > < >= <= != @location='UK'] */ function singleStep(dom,stepAction,stepStr){ var allArrData = [] ; var arrData = [] ; var num = stepAction.split(/\//).length ; recursiveNodes(allArrData,dom,num==2?1:999); stepStr = trim(stepStr) ; var nodeName ; var conds = true ; //判断单匹配 是否有 属性对比 [@..=..] if( /\[(.*?)\]/.test(stepStr) ){ nodeName = trim( /^(.*?)\[{1}/.exec(stepStr)[1] ) ; //属性 替换为 conds = /\[(.*?)\]/.exec(stepStr)[1].replace(/(@)(.*?)(?=\W)/g," allArrData[i].getAttribute('$2').toString() ") ; conds = conds.replace( /([\W]+)(.*?)::\'(.*?)\'/g," $1 /$3/g.test($2) " ) ; conds = conds.replace( /(text\(\))/g ," allArrData[i].innerHTML ") ; conds = conds.replace( /([\w\s])(=)/g ,"$2=") ; }else{ nodeName = stepStr ; }
for(var i=0;i<allArrData.length;i++){ if( new RegExp(nodeName, 'i').test( allArrData[i].nodeName ) && eval(conds) ){ arrData.push( allArrData[i] ); } } return arrData ; }
function getXpath(dom,xpathStr){ var xpaths = xpathStr.split(/(\/{1,2})/g); var arrDom = [dom] ; for(var i=1;i<xpaths.length;i=i+2){ var arrData = []; for(var j=0;j<arrDom.length;j++) arrData = arrData.concat( singleStep(arrDom[j],xpaths[i],xpaths[i+1]) ); arrDom = arrData ; } return arrDom ; }
Python is a dynamic object-oriented programming language that can be used for many kinds of software development.
It offers strong support for integration with other languages and tools, comes with extensive standard libraries, and can be learned in a few days. offers 提出 integration 综合 extensive 宽广 standard libraries 标准库
Many Python programmers report substantial productivity gains and feel the language encourages the development of higher quality, more maintainable code. report 宣告 substantial 实质 productivity 生产力
直接 运行 div_show_drag.rar http://www.blogjava.net/Files/Good-Game/div_Show_drag.rarhtml test <html> <head>
<script type="text/javascript" src="showDivUtil.js"></script>
</head>
<body>
<input type="button" id="_in" value="google-baidu" onclick="test();"/> <div id='_div' /> <script language="javascript"> /*api说明 ShowDiv( 源element , 是否使用现有 div ) 源element,是否使用现有 div 都可为null ; */ var ediv = new ShowDiv('_in',null);
function test(){ if( ! ediv.isShow ){ // tdiv[X,Y,H,W]准备展现div set->tdiv.X = .. , // tsubEle[X,Y,H,W] // 源ele大小位置 ,tscreen[screenH,screenW]屏幕长宽 ediv.setLocation = function(tdiv,tsubEle,tscreen){ /* 居中展现 tdiv.W =200 ; tdiv.H = 300 ; tdiv.X = tscreen.screenW/2-tdiv.W/2 ; tdiv.Y = tscreen.screenH/2-tdiv.H/2 ; */
/* 根据 tsubEle 位置 左显示 tdiv.X = tsubEle.X+tsubEle.W ; tdiv.Y = tsubEle.Y ; */
/* 根据 tsubEle 大小 左长条 显示 tdiv.X = tsubEle.X+tsubEle.W ; tdiv.Y = tsubEle.Y ; */ /* 根据 tsubEle 大小 下长条 显示 tdiv.X = tsubEle.X+tsubEle.W ; tdiv.Y = tsubEle.Y ; tdiv.H = 200 ; tdiv.W = tsubEle.W ; */ /* .. 等等 自己尝试吧*/ tdiv.innerHTML = "<li>google</li><li>baidu</li>" ; //可以参考 Drag.init(tdiv); } ediv.setStyle('background-color:#F4F4F4;'); ediv.show(); }else{ ediv.close(); //ediv.delete(); } }
</script> </body> </html>
showDivUtil.js /* * Skynet * 2008-9-15 00:56 * liukaiyi@gmail.com */ function ShowDiv(subEle,ediv){ //public this.style ; this.isShow = false ;
//private this._div ; this._subEle ; this._subEle ;
if( typeof ediv == "undefined" || ediv == null) this._div=document.createElement("div"); else if( typeof ediv == "string") this._div=document.getElementById(ediv); else if( /object/.test(typeof ediv) ) this._div= ediv ; if( typeof subEle == "string") this._subEle=document.getElementById(subEle); else if( /object/.test(typeof subEle) ) this._subEle= subEle ;
}
//外置方法 x , y ,w , h , div ShowDiv.prototype.setLocation = new Function() ;
//设置 div 样式 ShowDiv.prototype.setStyle=function(styleStrOrObj){ this.style=this._div.style ; if( typeof styleStrOrObj == "string"){ var strs = styleStrOrObj.split(/;/) ; for(var i=0;i<strs.length;i++){ var key = strs[i].split(/:/)[0]; var value = strs[i].split(/:/)[1]; var _s = key.indexOf("-") ; if( _s>0) key=key.substring(0,_s)+key.substring(_s+1,_s+2).toLocaleUpperCase()+key.substring(_s+2,key.length); if( key!=null&&key!=''&&key!=' ' ){ eval( 'this._div.style.'+key+'="'+value+'"' ); } } }else if( /object/.test(typeof styleStrOrObj) ) { this._div.style = styleStrOrObj ; } if(this._div.style.position==null || this._div.style.position=="") this._div.style.position="absolute"; } ShowDiv.prototype.show=function(){ if( typeof this._subEle != "undefined" || this._subEle != null){ this._subEle.Y = getElementPos(this._subEle).y; this._subEle.X = getElementPos(this._subEle).x ; this._subEle.W = this._subEle.offsetWidth ; this._subEle.H = this._subEle.offsetHeight ; } //this._div.Y = sset //this._div.X = sset this._div.W = parseInt( this._div.style.width ); this._div.H = parseInt( this._div.style.height ); this.setLocation(this._div,this._subEle,{screenW:document.body.clientWidth,screenH:document.body.clientHeight}); this._div.style.left = this._div.X ; this._div.style.top = this._div.Y ; if( this._div.W && this._div.H ){ this._div.style.width = this._div.W ; this._div.style.height = this._div.H ; } document.body.appendChild(this._div); this.isShow = true ; }
ShowDiv.prototype.close=function(){ document.body.removeChild(this._div); this.isShow = false ; }
ShowDiv.prototype.delete=function(){ document.body.removeChild(this._div); this._div = null ; this.isShow = false ; }
//得到 Element 位置 // 说明:用 Javascript 获取指定页面元素的位置 // 整理:http://www.codebit.cn // 来源:YUI DOM function getElementPos(el) { var ua = navigator.userAgent.toLowerCase(); var isOpera = (ua.indexOf('opera') != -1); var isIE = (ua.indexOf('msie') != -1 && !isOpera); // not opera spoof if(el.parentNode === null || el.style.display == 'none'){ return false; } var parent = null; var pos = []; var box;
if(el.getBoundingClientRect){ // IE box = el.getBoundingClientRect(); var scrollTop = Math.max(document.documentElement.scrollTop, document.body.scrollTop); var scrollLeft = Math.max(document.documentElement.scrollLeft, document.body.scrollLeft); return {x:box.left + scrollLeft, y:box.top + scrollTop}; }else if(document.getBoxObjectFor){ // gecko box = document.getBoxObjectFor(el); var borderLeft = (el.style.borderLeftWidth)?parseInt(el.style.borderLeftWidth):0; var borderTop = (el.style.borderTopWidth)?parseInt(el.style.borderTopWidth):0; pos = [box.x - borderLeft, box.y - borderTop]; }else { // safari & opera pos = [el.offsetLeft, el.offsetTop]; parent = el.offsetParent; if (parent != el) { while (parent) { pos[0] += parent.offsetLeft; pos[1] += parent.offsetTop; parent = parent.offsetParent; } } if (ua.indexOf('opera') != -1|| ( ua.indexOf('safari') != -1 && el.style.position == 'absolute' )){ pos[0] -= document.body.offsetLeft; pos[1] -= document.body.offsetTop; } } if (el.parentNode) { parent = el.parentNode; } else { parent = null; } // account for any scrolled ancestors while (parent && parent.tagName != 'BODY' && parent.tagName != 'HTML'){ pos[0] -= parent.scrollLeft; pos[1] -= parent.scrollTop; if (parent.parentNode) { parent = parent.parentNode; } else { parent = null; } } return {x:pos[0], y:pos[1]}; }
上面加上我的注解(希望能对大家理解有帮助): /************************************************** * dom-drag.js * 09.25.2001 * www.youngpup.net * Script featured on Dynamic Drive (http://www.dynamicdrive.com) 12.08.2005 ************************************************** * 10.28.2001 - fixed minor bug where events * sometimes fired off the handle, not the root. * 注解: Skynet * email : liukaiyi@gmail.com * blog : www.blogjava.net/Good-Game **************************************************/
var Drag = {
obj : null, /* api 说明: * 方法调用可以参考:http://www.dynamicdrive.com/dynamicindex11/domdrag/ * o 拖拽 Handle * oRoot 被拖拽 element (可选, 默认不填 o为被拖拽对象 type=object) * minX, maxX, minY, maxY 限制拖拽范围 (可选,默认不填为全屏 type=int ) * bSwapHorzRef, bSwapVertRef 判断是否允许 横,纵向拖拽(可选,默认不填无限制 type=boolean ) * fXMapper(x), fYMapper(y) 为外置函数 拖拽效果体现前调用 (x,y) 为当前element位置(可选 type=Function) */ init : function(o, oRoot, minX, maxX, minY, maxY, bSwapHorzRef, bSwapVertRef, fXMapper, fYMapper) { /* 拖拽事件 挂载 (本js 主线 生命周期 描述) * 1. 预定 o.onmousedown事件触发运行 Drag.start。 * 2. 触发 element-> onmousedown->Drag.start * 2.1 先得到 element 当前"改变初"位置,记入到 o.lastMouseX ;o.lastMouseY,挂载Drag.obj,Darp.root 为当前 element。 * 2.2 预定 document.onmousemove = Drag.drag; document.onmouseup = Drag.end。 * 3. 触发 document.onmousemove 运行 Drag.drag-> 拖拽效果体现。 * 4. 触发 document.onmouseup 运行 Drag.end-> 挂载 document.onmousemove;document.onmouseup;Drag.obj取消。 */ o.onmousedown = Drag.start; //是否能 横,纵向拖拽 o.hmode = bSwapHorzRef ? false : true ; o.vmode = bSwapVertRef ? false : true ; //挂载 o.root o.root = oRoot && oRoot != null ? oRoot : o ; if (o.hmode && isNaN(parseInt(o.root.style.left ))) o.root.style.left = "0px"; if (o.vmode && isNaN(parseInt(o.root.style.top ))) o.root.style.top = "0px"; if (!o.hmode && isNaN(parseInt(o.root.style.right ))) o.root.style.right = "0px"; if (!o.vmode && isNaN(parseInt(o.root.style.bottom))) o.root.style.bottom = "0px"; // 限定 移动范围 o.minX = typeof minX != 'undefined' ? minX : null; o.minY = typeof minY != 'undefined' ? minY : null; o.maxX = typeof maxX != 'undefined' ? maxX : null; o.maxY = typeof maxY != 'undefined' ? maxY : null;
o.xMapper = fXMapper ? fXMapper : null; o.yMapper = fYMapper ? fYMapper : null; /*自定义拖拽-事件添加(相当于我们在java中的 抽象类 中未实现的方法 比如: * obj.onDrag = function(x, y) { * scrolldiv.style.top=y * (-1) +"px"; * } */ o.root.onDragStart = new Function(); o.root.onDragEnd = new Function(); o.root.onDrag = new Function(); },
//由 function init >> o.onmousedown = Drag.start; start : function(e) { //得到被拖拽 element var o = Drag.obj = this; e = Drag.fixE(e); //element 移动初位置 var y = parseInt(o.vmode ? o.root.style.top : o.root.style.bottom); var x = parseInt(o.hmode ? o.root.style.left : o.root.style.right ); //可能的外置函数调用 o.root.onDragStart(x, y); //event 初位置 记入 o.lastMouseX = e.clientX; o.lastMouseY = e.clientY; if (o.hmode) { if (o.minX != null) o.minMouseX = e.clientX - x + o.minX; if (o.maxX != null) o.maxMouseX = o.minMouseX + o.maxX - o.minX; } else { if (o.minX != null) o.maxMouseX = -o.minX + e.clientX + x; if (o.maxX != null) o.minMouseX = -o.maxX + e.clientX + x; }
if (o.vmode) { if (o.minY != null) o.minMouseY = e.clientY - y + o.minY; if (o.maxY != null) o.maxMouseY = o.minMouseY + o.maxY - o.minY; } else { if (o.minY != null) o.maxMouseY = -o.minY + e.clientY + y; if (o.maxY != null) o.minMouseY = -o.maxY + e.clientY + y; } /*>>>>>>>>>>>比较关键的挂载<<<<<<<<<<<<<< * * 使用 document.onmousemove 事件 而不使用 element的,是应为当拖动太快,可能会脱离element. */ document.onmousemove = Drag.drag; document.onmouseup = Drag.end;
return false; },
//由 function start>> document.onmousemove = Drag.drag; drag : function(e) { e = Drag.fixE(e); var o = Drag.obj;
var ey = e.clientY; var ex = e.clientX; //得到 element 当前位置(vmode,hmode判断是否可以横纵向拖拽) var y = parseInt(o.vmode ? o.root.style.top : o.root.style.bottom); var x = parseInt(o.hmode ? o.root.style.left : o.root.style.right ); var nx, ny; if (o.minX != null) ex = o.hmode ? Math.max(ex, o.minMouseX) : Math.min(ex, o.maxMouseX); if (o.maxX != null) ex = o.hmode ? Math.min(ex, o.maxMouseX) : Math.max(ex, o.minMouseX); if (o.minY != null) ey = o.vmode ? Math.max(ey, o.minMouseY) : Math.min(ey, o.maxMouseY); if (o.maxY != null) ey = o.vmode ? Math.min(ey, o.maxMouseY) : Math.max(ey, o.minMouseY); //本js中 最主要的地方: //得到 鼠标移动 向量 drap(x,y) = fun_drap:event(x,y) - fun_start:event(x,y) //并于 得到拖拽效果: element(x,y) + drap(x,y) nx = x + ((ex - o.lastMouseX) * (o.hmode ? 1 : -1)); ny = y + ((ey - o.lastMouseY) * (o.vmode ? 1 : -1));
if (o.xMapper) nx = o.xMapper(y) else if (o.yMapper) ny = o.yMapper(x) //效果体现 Drag.obj.root.style[o.hmode ? "left" : "right"] = nx + "px"; Drag.obj.root.style[o.vmode ? "top" : "bottom"] = ny + "px"; Drag.obj.lastMouseX = ex; Drag.obj.lastMouseY = ey; //调用外置函数 Drag.obj.root.onDrag(nx, ny); return false; }, //由 function start>> document.onmouseup = Drag.end; end : function() { document.onmousemove = null; document.onmouseup = null; Drag.obj.root.onDragEnd( parseInt(Drag.obj.root.style[Drag.obj.hmode ? "left" : "right"]), parseInt(Drag.obj.root.style[Drag.obj.vmode ? "top" : "bottom"])); Drag.obj = null; }, //跨 浏览器 得到 event fixE : function(e) { if (typeof e == 'undefined') e = window.event; if (typeof e.layerX == 'undefined') e.layerX = e.offsetX; if (typeof e.layerY == 'undefined') e.layerY = e.offsetY; return e; } };
参考: http://neil-jh.javaeye.com/blog/199345 效果:
google
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@taglib uri="/struts-tags" prefix="s"%> <%@taglib uri="http://java.sun.com/jstl/core_rt" prefix="c"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <li> <!-- 类中静态变量 --> <s:property value="%{@action.SsdAction@GOOD}"/> <!-- 调用 方法 --> <s:set name="num" value="20" /> <s:set name="listData" value="%{ ssdMethod.getBeans(#num) }" /> <!-- 和 jstl 配合使用 --> <select> <c:forEach var="btmp" items="${listData}"> <option value="${btmp.id} }">${btmp.name}</option> </c:forEach> </select> <!-- 调用枚举类 public enum Type { //id value : gget sset g1(1,"test1"), g2(2,"test2"), g3(3,"test3"); . --> <s:select list="%{ @myEnum.Type@values() }" listKey="id" listValue="value" />
<!-- 循环遍历 添加逻辑 ..{?#this.id>2 } --> <s:select list="%{ @myEnum.Type@values().{?#this.id>2 } }" listKey="id" listValue="value" />
</li>
</body> </html>
haptic 触觉 --of or relating to the sensation of touch. --关于 触动 感觉。
haptics is the science of applying tactile sensation to humen interaction with computers . 字面翻译: 触觉论 是 一种 科学 申请 触觉 与 人类 互动 和 电脑 : 触觉论 是将人类的接触感觉应用与计算机连接的一门科学。
A haptic device is one that involves physical contact between the computer and the user . 》》一个触觉设备 是一个 涉及 物理 连接 在 电脑 和 人 》》一个触觉设备包含 计算机和用户之间的物理连接
usually through an input/output device,such as a joystick or data gloves ,that senses the body,s movements. 》》通常 通过 一个 输入/输出 设备 , 比如 一个 操纵杆 或 数据手套 , 这些设备 感觉 身体的移动 。
主页:http://code.google.com/apis/protocolbuffers/docs/overview.html testProto.proto package foo.bar; option java_package = "com.proto";
message Person { required string name = 1; required int32 id = 2; optional string email = 3;
enum PhoneType { MOBILE = 0; HOME = 1; WORK = 2; }
message PhoneNumber { required string number = 1; optional PhoneType type = 2 [default = HOME]; }
repeated PhoneNumber phone = 4; }
运行命令 '/home/kaiyi/proto/bin/protoc' --java_out=src testProto.proto 使用( 本类可用,builder 可改,开用但 list 删除要使用比较郁闷的方法删除!) package unit;
import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List;
import com.google.protobuf.InvalidProtocolBufferException; import com.proto.TestProto; import com.proto.TestProto.Person; import com.proto.TestProto.Person.PhoneNumber;
public class Main { public static void main(String[] args) throws InvalidProtocolBufferException { //空创建 Person.Builder builder = Person.newBuilder(); builder.setName("liukaiyi"); builder.setId(1); builder.setEmail("email"); PhoneNumber.Builder pBuilder1 = PhoneNumber.newBuilder(); pBuilder1.setNumber("1"); pBuilder1.setType(TestProto.Person.PhoneType.MOBILE); PhoneNumber.Builder pBuilder2 = PhoneNumber.newBuilder(); pBuilder2.setNumber("2"); pBuilder2.setType(TestProto.Person.PhoneType.HOME); builder.addPhone(pBuilder1); builder.addPhone(pBuilder2); //此处为存储到数据库 或 传输! byte[] data = builder.build().toByteArray() ; for(byte tb : data ) System.out.print( (char)tb ); //组建 Person person = Person.parseFrom(data); Person.Builder builder2 = Person.newBuilder(person); builder2.setEmail("test"); PhoneNumber.Builder pBuilder3 = PhoneNumber.newBuilder(); pBuilder3.setNumber("3"); pBuilder3.setType(TestProto.Person.PhoneType.HOME); builder2.addPhone(pBuilder3); //这 我最不明白的地方 , list 这 只能 使用 这种方法才可以删除 list ???? List list = new ArrayList(builder2.getPhoneList()); List<PhoneNumber> ltmp = builder2.getPhoneList() ; for(int i=0;i<list.size();i++ ){ if(ltmp.get(i).getNumber().equals("2")) list.remove( ltmp.get(i) ) ; } builder2.clearPhone().addAllPhone(list); builder2.clearEmail();
System.out.println(list.size()); System.out.println(); byte[] data2 = builder2.build().toByteArray() ; for(byte tb : data2 ) System.out.print( (char)tb ); } }
<?
xml version="1.0" encoding="utf8"
?>
<%
@ page language
=
"
java
"
contentType
=
"
text/html; charset=utf8
"
pageEncoding
=
"
utf8
"
%>
<%
@taglib uri
=
"
/WEB-INF/struts-tags.tld
"
prefix
=
"
s
"
%>
<%
@taglib uri
=
"
/WEB-INF/ljw.tld
"
prefix
=
"
ljw
"
%>
<%
@page import
=
"
com.ljw.bean.CorrectionWrong
"
%>
<%
@page import
=
"
com.ljw.bean.CorrectionWrong.State
"
%>
<%
@page import
=
"
com.opensymphony.xwork2.util.ValueStack
"
%>
<
html
xmlns
="http://www.w3.org/1999/xhtml"
>
<
head
>
<
meta
http-equiv
="Content-Type"
content
="text/html; charset=utf8"
/>
<
title
>
Insert title here
</
title
>
<
script
type
="text/javascript"
src
="../js/prototype.js"
></
script
>
<
script
type
="text/javascript"
src
="../js/jsMsg.jsp"
></
script
>
<
script
type
="text/javascript"
src
="../js/comm.js"
></
script
>
<
SCRIPT
language
=JavaScript
src
="../js/supertable/dialog.js"
type
=Text/JavaScript
></
SCRIPT
>
</
head
>
<
body
>
<
div
id
="communityDiv"
>
<
s:set
name
=""
></
s:set
>
<
s:iterator
id
="d"
value
="%{pageList.objectList}"
>
用户名字:
<
s:property
value
="#d.userInfo.userName"
/><
br
>
url:
<
s:property
value
="#d.url"
/><
br
>
状态:
<
s:property
value
="#d.ecwState.value"
/><
br
>
纠错:
<
s:property
value
="#d.cwArticle"
/></
br
>
编辑输入:
<
textarea
rows
="10"
cols
="50"
id
='<s:property
value
="#d.id"
/>
' >
<
s:property
value
="#d.boardmasterDesc"
/></
textarea
>
<
input
type
="button"
onclick
="getUpdate('<s:property value="
#d.id"
/>
')"/>
<
hr
/>
</
s:iterator
>
<
br
/>
<
ljw:pages
value
="%{pageList.pages}"
javaScript
="loadCommunityListUrl"
/>
</
div
>
</
body
>
<
script
type
="text/javascript"
>
function
loadCommunityListUrl(url) { $('communityDiv').innerHTML
=
pageLoadingCenter;
var
urls
=
getActionName(url);
var
pars
=
getActionPars(url);
var
myAjax
=
new
Ajax.Updater(
"
communityDiv
"
, urls, {method: 'post', parameters: pars}); }
var
request
=
false
;
try
{ request
=
new
XMLHttpRequest(); }
catch
(trymicrosoft) {
try
{ request
=
new
ActiveXObject(
"
Msxml2.XMLHTTP
"
); }
catch
(othermicrosoft) {
try
{ request
=
new
ActiveXObject(
"
Microsoft.XMLHTTP
"
); }
catch
(failed) { request
=
false
; } } }
if
(
!
request) alert(
"
Error initializing XMLHttpRequest!
"
);
var
_robj
=
null
;
function
getUpdate(ki) { _robj
=
document.getElementById(ki) ;
var
urls
=
'cwmain.
do
';
var
pars
=
'c
=
ajaxUpdateByBoardMaster
&
cwId
=
'
+
ki
+
'
&
boardMasterDesc
=
'
+
_robj.value ; request.open(
"
POST
"
, urls,
true
); request.setRequestHeader(
"
Cache-Control
"
,
"
no-cache
"
); request.setRequestHeader(
"
content-type
"
,
"
application/x-www-form-urlencoded
"
); request.send(pars); request.onreadystatechange
=
updatePage;
}
function
updatePage() {
if
(request.readyState
==
4
) {
if
(request.status
==
200
||
request.status
==
0
) { alert(request.responseText); eval('
var
ajaxData
=
'
+
request.responseText);
if
( ajaxData.isUpdate ){ alert( '更新成功!' ); }
else
{ alert( '更新不成功!' ); } } } }
</
script
>
</
html
>
<
html
>
<
head
><
title
>
拖动效果函数演示 by Longbill.cn
</
title
>
<
style
>
div
{
position
:
absolute
;
background-color
:
#c3d9ff
;
margin
:
0px
;
padding
:
5px
;
border
:
0px
;
width
:
100px
;
height
:
100px
;
}
</
style
>
</
head
>
<
body
>
<
script
>
function
drag(o,s) {
if
(
typeof
o
==
"
string
"
) o
=
document.getElementById(o); o.orig_x
=
parseInt(o.style.left)
-
document.body.scrollLeft; o.orig_y
=
parseInt(o.style.top)
-
document.body.scrollTop; o.orig_index
=
o.style.zIndex; o.onmousedown
=
function
(a) {
this
.style.cursor
=
"
move
"
;
this
.style.zIndex
=
10000
;
var
d
=
document;
if
(
!
a)a
=
window.event;
var
x
=
a.clientX
+
d.body.scrollLeft
-
o.offsetLeft;
var
y
=
a.clientY
+
d.body.scrollTop
-
o.offsetTop;
//
author: www.longbill.cn
d.ondragstart
=
"
return false;
"
d.onselectstart
=
"
return false;
"
d.onselect
=
"
document.selection.empty();
"
if
(o.setCapture) o.setCapture();
else
if
(window.captureEvents) window.captureEvents(Event.MOUSEMOVE
|
Event.MOUSEUP);
d.onmousemove
=
function
(a) {
if
(
!
a)a
=
window.event; o.style.left
=
a.clientX
+
document.body.scrollLeft
-
x; o.style.top
=
a.clientY
+
document.body.scrollTop
-
y; o.orig_x
=
parseInt(o.style.left)
-
document.body.scrollLeft; o.orig_y
=
parseInt(o.style.top)
-
document.body.scrollTop; }
d.onmouseup
=
function
() {
if
(o.releaseCapture) o.releaseCapture();
else
if
(window.captureEvents) window.captureEvents(Event.MOUSEMOVE
|
Event.MOUSEUP); d.onmousemove
=
null
; d.onmouseup
=
null
; d.ondragstart
=
null
; d.onselectstart
=
null
; d.onselect
=
null
; o.style.cursor
=
"
normal
"
; o.style.zIndex
=
o.orig_index; } }
if
(s) {
var
orig_scroll
=
window.onscroll
?
window.onscroll:
function
(){}; window.onscroll
=
function
() { orig_scroll(); o.style.left
=
o.orig_x
+
document.body.scrollLeft; o.style.top
=
o.orig_y
+
document.body.scrollTop; } } }
</
script
>
<
div
id
="div1"
style
="left:10px;top:10px;"
>
div1:我可以被拖动
</
div
>
<
div
id
="div2"
style
="left:120px;top:10px;background-color : #f3d9ff"
>
div2:来拖我呀
</
div
>
<
div
id
="div3"
style
="left:230px;top:10px;background-color : #c3ffff"
>
div3:我随便你拖
</
div
>
<
div
id
="div4"
style
="left:10px;top:120px;background-color : #c3d944"
>
div4:我可以随窗口滑动,把我拖到最下面,然后滚动网页看看
</
div
>
<
div
id
="div5"
style
="left:120px;top:120px;background-color : #f3d944"
>
作者: Longbill
<
a
href
=http://www.longbill.cn
target
=_blank
>
www.longbill.cn
</
a
>
</
div
>
<
div
id
="div6"
style
="left:230px;top:120px;background-color : #e3f944;width:200px;"
>
参数说明: drag(obj [,scroll]); obj:对象的id或对象本身; scroll(可选):对象是否随窗口拖动而滑动,默认为否 鼠标右键查看源代码
</
div
>
<
script
>
drag(
"
div1
"
); drag(
"
div2
"
); drag(
"
div3
"
); drag(
"
div4
"
,
1
); drag(
"
div5
"
,
1
); drag(
"
div6
"
,
1
);
</
script
>
</
body
>
demo 下载: http://www.blogjava.net/Files/Good-Game/div_.rar 运行 div.html html: <html> <head> <script type="text/javascript" src="prototype.js"></script> <script type="text/javascript" src="drag.js"></script> <META http-equiv=Content-Type content="text/html; charset=utf8"> </head>
<body> <a onclick="getDrag(event, 'ajax.html?id=5', 'position:absolute;display:none;left:50; top:10; z-index:1000; padding:0px; background-color:#FFFFCC; color:#201000; font-size:12px; border:5px solid #284860;', 'background-color:#CCFFCC;')">测试使用(请点击) </a> </body> </html> js. // 参考 : http://hi.baidu.com/foxlively/blog/item/0ce341b3f0c050a2d8335af8.html // 使用 : prototype.js //使用方法 var _div1 = null; var _style2 = null;
function getDrag(event, url,divId, style1, style2) { if (style2) _style2 = style2; else _style2 = ""; if(divId==null) _div1 = document.createElement("div"); else _div1 = document.getElementById(divId); _div1.style.position = 'absolute'; _div1.style.display = 'none';
if (_div1.style.border == null || _div1.style.border == '') _div1.style.border = '1px solid #284860';
if (style1) _div1.setAttribute('style', style1); actionAjax(url); document.body.appendChild(_div1); showByEvent(event, _div1); }
function getActionName(url) { var question = url.indexOf("?"); if (question > 0) { return url.substring(0, question); } else { return url; } }
function getActionPars(url) { var question = url.indexOf("?"); if (question > 0) { return url.substring(question+1, url.length); } else { var d = new Date(); var t = d.getTime(); return "timestamp="+t; } }
function actionAjax(url) { var urls = getActionName(url); var pars = getActionPars(url); var myAjax = new Ajax.Updater(_div1, urls, { method :'post', parameters :pars, onComplete :_action }); }
function _action(req) { var varhtml = "<div id=\"_drag_div\" style=\"" + _style2 + "\" align=\"right\"><br/><a href=\"javascript:;\" onclick=\"this.parentNode.parentNode.style.display='none';this.parentNode.parentNode.innerHTML=null;\">[关闭]</a></div>" + req.responseText +"<div id=\"_drag_div\" style=\"" + _style2 + "\" align=\"left\"><br/><a href=\"javascript:;\" onclick=\"this.parentNode.parentNode.style.display='none';this.parentNode.parentNode.innerHTML=null;\">[关闭]</a></div>" ; //varhtml = varhtml.replace(/form[ ]+action=["'](.*)["']/gi, "form action=\"javascript:actionAjax('$1');\" ") ; _div1.innerHTML = varhtml; var drag = new Drag(); // drag.build(div1);//拖动本身 drag.build(_div1, _div1.firstChild);// 通过一个对象拖动另一个对象 //drag.build(_div1, _div1.lastChild);// 通过一个对象拖动另一个对象 }
function showByEvent(event, useDiv) { useDiv.style.display = ""; useDiv.style.left = mouseX(event); useDiv.style.top = mouseY(event); }
function mouseX(ev) { if( ev == null )ev = event || window.event ; if(ev.clientX){ return ev.clientX + document.body.scrollLeft - document.body.clientLeft; }else if(ev.pageX){ return ev.pageX; } } function mouseY(ev) { if( ev == null )ev = event || window.event ; if(ev.clientY){ return ev.clientY + document.body.scrollTop - document.body.clientTop ; }else if(ev.pageX){ return ev.pageY; } }
function Drag() { } Drag.prototype.baseX = 0; Drag.prototype.baseY = 0; Drag.prototype.lastX = 0; Drag.prototype.lastY = 0; Drag.prototype.nowX = 0; Drag.prototype.nowY = 0; Drag.prototype.obD = null; Drag.prototype.obM = null; Drag.prototype.build = function(_obD, _obM) { if (_obM) { Drag.prototype.obM = _obM; } else { Drag.prototype.obM = _obD; } Drag.prototype.obD = _obD; Drag.prototype.obM.onmousedown = function(event) { Drag.prototype.lastX = mouseX(event); Drag.prototype.lastY = mouseY(event); Drag.prototype.baseX = Drag.prototype.obD.style.left; Drag.prototype.baseY = Drag.prototype.obD.style.top; this.onmousemove = function(event) { Drag.prototype.nowX = mouseX(event); Drag.prototype.nowY = mouseY(event); Drag.prototype.obD.style.left = (parseFloat(Drag.prototype.baseX) + Drag.prototype.nowX - Drag.prototype.lastX) + "px"; Drag.prototype.obD.style.top = (parseFloat(Drag.prototype.baseY) + Drag.prototype.nowY - Drag.prototype.lastY) + "px"; } } Drag.prototype.obM.onmouseup = function(event) { // obD.onmouseup = null; Drag.prototype.obD.onmousemove = null; Drag.prototype.obM.onmousemove = null; } Drag.prototype.obM.onmouseout = function() { // obM.onmouseup = null Drag.prototype.obM.onmousemove = null; Drag.prototype.obD.onmousemove = null; } }
参考: http://www.programbbs.com/bbs/view25-12320-1.htm但上面的 一些sql语句 ,有查询时间问题,在此我已于改正了并希望和大家分享。 ---------自我感觉 第四题 很不错!----------------------------------------------------------------------------------- 第一题(只要重复的都要 输出) ---------------------------------------------------------------------- create table c (id int ); insert into c values (1),(2),(3),(4),(3),(5),(6),(1); 结果: select id from c group by id having count(id)>1 ;
附加(查询重复最多的倒排) select bid,count(bid) as cu from tb group by bid having count(bid)>1 order by cu desc ---------------------------------------------------------------------- 第二题(报表查询横向输出) 查询后的结果: Create table d(id int,name varchar(50)); insert into d values(1,'gly'); insert into d values(2,'ptgly'); insert into d values(3,'ybgly'); insert into d values(4,'ptgly'); insert into d values(5,'ybgly'); +---+-----+------+ |gly|ptgly|ybgly | |---+-----+------+- |1 |2 |2 | +---+-----+------+ ----------------------------------------------------------------------- select sum(case when name='gly' then 1 else 0 end ) as gly , sum(case when name='ptgly' then 1 else 0 end ) as ptgly , sum(case when name='ybgly' then 1 else 0 end ) as ybgly from d ;
第三题 可以根据上面 2,4 可以得出 。 下面我们详细说下 4题。 ----------------------------------------------------------------------- 第四题(复杂组合查询!) create table table_a (No int, No2 int,num double,itime date); insert into table_a values (1234,567890,33.5,'2004-12-21'), (1234,598701,44.8,'2004-11-21'), (1234,598701,45.2,'2004-10-01'), (1234,567890,66.5,'2004-9-21'), (3456,789065,22.5,'2004-10-01'), (3456,789065,77.5,'2004-10-27'), (3456,678901,48.5,'2004-12-21'); 按月统计销售表中货物的销售量数 查询结果如下: No, No2 , 九月, 十月,十一月,十二月 1234,567890, 66.5 , 0 , 0 , 33.5 1234,598701, 0 , 45.2, 44.8, 0 3456,789065, 0 , 100, 0 , 0 3456,678901, 0 , 0, 0 , 48.5 ----------------------------------------------------------------------- //当然也可以 使用mysql 时间函数 在软件编辑时 你可以输入 String[] 并根据数据动态拼写 sql( case部分!! ) //这个 例子很好 哦!报表可以一句sql 得出! select NO,NO2, sum(case when itime like '2004-%9%' then num else 0 end) as 9M, sum(case when itime like '2004-10%' then num else 0 end) as 10M, sum(case when itime like '2004-11%' then num else 0 end) as 11M, sum(case when itime like '2004-12%' then num else 0 end) as 12M from table_a group by no,no2 order by no,no2 ;
-------------------------------------------------------------- 第五题 代码,名称 1 a 2 b 11 c (代码11表示为1的下级) 我要通过一条句子,得出如下结果: 代码,名称,有无下级 1 a 有 2 b 无 11 c 无 Create table TabTest(t_Code varchar(10),t_Name varchar(10)); insert into TabTest values('1','a'); insert into TabTest values('2','b'); insert into TabTest values('11','c'); -------------------------------------------------------------- select tt1.t_Code,tt1.t_name,( case when exists (select 1 from tabtest tt2 where tt2.t_code like CONCAT(tt1.t_code,'%') and tt2.t_code <> tt1.t_code ) then 'you' else 'wu' end ) as you_wu from tabtest tt1 ;
官方 http://jsptags.com/tags/navigation/pager/index.jsp先向 demo 页面样式: ######################################################################################## request.getParameter 中参数
'pager.offset'=6 <%@ page session="false" %> <%@ taglib uri="http://jsptags.com/tags/navigation/pager" prefix="pg" %> <%@ page contentType="text/html; charset=gb2312"%> <html> <head> <title>Pager Tag Library Demo</title> <meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<!-- 参数展现 --> request.getParameter 中参数<br/> <%for(Object otmp : request.getParameterMap().keySet() ){%> <%="'"+otmp.toString()+"'"%>=<%=request.getParameter(otmp.toString())%><br\> <%}%>
<form action="<%= request.getRequestURI() %>" method="get"> <br/> <!-- items=数据总条?? index=分页标明展现格式;"center", "forward" or "half-full". maxPageItems=每页最大展现行数; maxIndexPages=每页最大可选页数; isOffset=数据是否展现; scope=参数作用范围;
-->
<pg:pager items="<%= webPalette.length %>" index="<%= "center" %>" maxPageItems="<%= 3 %>" maxIndexPages="<%= 10 %>" isOffset="<%= true %>" export="offset,currentPageNumber=pageNumber" scope="request">
<br/>分页中标签中隐含属性 'offset'=<%=offset%><br/>
<!-- 分页需要向下传递的参数; 比如组合查询使用参数. 此为get提交;乱码问题特别注意; 如:parameter(google) 参数由本页面传递给下一分页页面; --> <pg:param name="google"/>
<!-- 分页具体表现页面 --> <pg:index> <jsp:include page="/WEB-INF/jsp/texticon.jsp" flush="true"/> </pg:index>
<hr> <table width="90%" cellspacing="4" cellpadding="4"> <%for (int i = offset.intValue(),l = Math.min(i + 10, webPalette.length);i < l; i++){%> <pg:item> <tr><th bgcolor="<%= webPalette[i][0] %>"><font color="<%= webPalette[i][1] %>"><%= i + 1 %></font></th></tr> </pg:item> <%}%> </table> <hr>
<pg:index> <jsp:include page="/WEB-INF/jsp/texticon.jsp" flush="true"/> </pg:index>
</pg:pager> </center> </body> </html>
<%! private static final String BLACK = "#000000", WHITE = "#ffffff"; private static final String[][] webPalette = { { WHITE, BLACK}, {"#cccccc",BLACK}, {"#999999",BLACK}, {"#666666",WHITE}, {"#333333",WHITE}, { BLACK, WHITE}, {"#ffcc00",BLACK}, {"#ff9900",BLACK}, {"#ff6600",BLACK}, {"#ff3300",WHITE}, {"#99cc00",BLACK}, {"#cc9900",BLACK}, {"#ffcc33",BLACK}, {"#ffcc66",BLACK}, {"#ff9966",BLACK}, {"#ff6633",BLACK}, {"#cc3300",WHITE}, {"#cc0033",WHITE}, {"#ccff00",BLACK}, {"#ccff33",BLACK}, {"#333300",WHITE} };
private static final String getParam(ServletRequest request, String name, String defval) { String param = request.getParameter(name); return (param != null ? param : defval); }
private static final int getParam(ServletRequest request, String name, int defval) { String param = request.getParameter(name); int value = defval; if (param != null) { try { value = Integer.parseInt(param); } catch (NumberFormatException ignore) { } } return value; }
%>
<!-- 分页具体表现页面 -->
<%@ page session="false" %> <%@ taglib uri="http://jsptags.com/tags/navigation/pager" prefix="pg" %>
<jsp:useBean id="currentPageNumber" type="java.lang.Integer" scope="request"/>
<font face="fixed">
<!-- 到第一页 --> <pg:first export="firstPageUrl=pageUrl" unless="current"> <a href="<%= firstPageUrl %>"> |< </a> </pg:first>
<!-- 每次后退跳10页 --> <pg:skip export="skipBackPageUrl=pageUrl" pages="<%= -10 %>"> <a href="<%= skipBackPageUrl %>"><<<</a> </pg:skip>
<!-- 每次后退跳 1 页 --> <pg:prev export="prevPageUrl=pageUrl"> <a href="<%= prevPageUrl %>"><<</a> </pg:prev>
<!-- 定位 跳页数 --> <pg:pages><% if (pageNumber == currentPageNumber) { %> <b><%= pageNumber %></b> <% } else { %> <a href="<%= pageUrl %>"><%= pageNumber %></a> <% } %></pg:pages>
<!-- 每次前进跳 1 页 --> <pg:next export="nextPageUrl=pageUrl"> <a href="<%= nextPageUrl %>">>></a> </pg:next>
<!-- 每次后前进10页 --> <pg:skip export="skipForwardPageUrl=pageUrl" pages="<%= 10 %>"> <a href="<%= skipForwardPageUrl %>">>>></a> </pg:skip>
<!-- 到最后页 --> <pg:last export="lastPageUrl=pageUrl" unless="current"> <a href="<%= lastPageUrl %>">>|</a> </pg:last>
</font>
-> http://displaytag.sourceforge.net分页流程描述: 1.组合查询参数得取。 比如时间范围,用户名模糊查询。。这些存入 session->data;name 2.通过持久层得到 ‘数据总条数’‘当前展现页数据’; 3.分页点击;根据session 组合参数,再次向数据库申请书及。 代码: <jsp:root version="1.2" xmlns:jsp="http://java.sun.com/JSP/Page" xmlns:display="urn:jsptld:http://displaytag.sf.net"> <jsp:directive.page import="java.util.regex.Pattern" /> <jsp:directive.page import="test.Bean" /> <jsp:directive.page import="java.util.ArrayList" /> <jsp:directive.page import="java.util.List" /> <jsp:directive.page contentType="text/html; charset=UTF-8" /> <jsp:include page="inc/header.jsp" flush="true" />
<jsp:scriptlet> <![CDATA[
Pattern pattern = Pattern.compile("d-[0-9]+-p"); String pageIndexName = null ; for(Object otmp : request.getParameterMap().keySet() ){ if( pattern.matcher(otmp.toString()).find() ){ pageIndexName = otmp.toString(); break; } } int pageSize = 10; //每页显示的条数 int pageIndex = 0 ; if(pageIndexName!=null){ pageIndex = (request.getParameter(pageIndexName)==null)? 0:(Integer.parseInt(request.getParameter(pageIndexName)) - 1); //当前页数 } List list = new ArrayList(); for(int i=0;i<pageSize;i++){ list.add( new Bean(pageIndex*10+i,"liu-"+pageIndex*10+i) ); } request.setAttribute("data",list); session.setAttribute( "resultSize", 100 ); out.print("!"+pageIndexName);
]]></jsp:scriptlet>
<h2>数据分页展现开始</h2> <display:table name="data" pagesize="10" partialList="true" size="sessionScope.resultSize"> <display:column property="id" title="ID"></display:column> <display:column property="name" title="名字"></display:column> </display:table> <jsp:include page="inc/footer.jsp" flush="true" />
</jsp:root>
项目开发:就好像是一个取得真理的一个过程。 在开始“没有人”会知道什么是对的,什么是错的。所谓的客户(中世纪教会的教徒),告诉你月亮是“热胀冷缩”造成的“阴晴圆缺”。 在初期你敢于否定“热胀冷缩”原理?或者说根本就是认为月亮是受“热胀冷缩”原理影响的。 那好,下面我们根据月亮圆缺原理,写个统计温度与月亮亮度报表。
客户自己想要的东西也是一个认知的过程。编码要在开始就要确定是在一个不稳定的环境(即使错了我也能容易修改,这是软件最有价值的地方)。对于这些理解为项目的可变性总结出的一些见解: 1.尽量明确各层使用框架。这样能统一技术,明确编码风格,统一存放,查找地址。这样就能很好的 定位要修改文件的物理地址和 尽量不与个人技术有关 。 2.尽量明确各种动作的命名规范。这样不但能很好的使用 aop ,而且为修改提供了 逻辑地址查找提供便利。 3.减少个人英雄主义。由于某些个人原因,引入与项目不兼容的技术,这是很危险的。只有这为“英雄”能修改的后果很严重。 4.编码中对“可预见性”的代码结构适应,扩展接口预留。月亮缺失可能不是“热胀冷缩”引起的怎么办(当然也是最难做到)这只要编码想到可能就有“可变性”就要有好的相应对策,比如:公司鼓励程序员的为“可变性预留接口”,当然最好也注意下预留接口的 规范 。
参考引用: 主题:使用全功能Tomcat简化调试让classpath参数走开直接用eclipse 调试 : tomcat - > service.xml <Context debug="5" docBase="E:/tomcat/tomcatwebroot" path="/tomcatwebroot" reloadable="true" privileged="true"> </Context>这引入一个java 文件 到你的 工程中 import java.io.File; import java.io.FileFilter; import java.lang.reflect.Method; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.List;
public class MainClassLoad { //commons-lang-2.0.jar static String TOMCAT_HOME = "D:\\apache\\apache-tomcat-5.5.20\\apache-tomcat-5.5.20";
public static void main(String[] args) throws Exception { System.setProperty("catalina.home", TOMCAT_HOME); final ClassLoader classLoader = getClassLoader(new String[]{ TOMCAT_HOME+"\\common\\lib", TOMCAT_HOME+"\\server\\lib", TOMCAT_HOME+"\\bin" }); Object obj = getObject(classLoader,"org.apache.catalina.startup.Catalina"); Method setConfig = obj.getClass().getMethod("setConfig", new Class[]{String.class}); setConfig.invoke(obj, TOMCAT_HOME + "/conf/server.xml"); Method start = obj.getClass().getMethod("start", new Class[]{}); start.invoke(obj, null); } public static Object getObject(ClassLoader classLoader,String className) throws Exception{ return classLoader.loadClass(className).newInstance(); }
public static ClassLoader getClassLoader(String[] libPath) throws Exception{ List<URL> list = new ArrayList<URL>(); FileFilter fileFilter = new FileFilter() { public boolean accept(File dir) { String name = dir.getName().toLowerCase(); return name.endsWith("jar") || name.endsWith("zip"); } }; for(String stmp : libPath){ for(File ftmp : new File(stmp).listFiles(fileFilter) ){ list.add( new URL("file",null,ftmp.getPath()) ); } } URL[] urls = new URL[list.size()]; // fill the urls array with URLs to library files found in libRoot for(int i = 0; i < list.size(); i++) { urls[i] = new URL("file",null,list.get(i).getPath() ); } ClassLoader classLoader = new URLClassLoader(urls, Thread.currentThread(). getContextClassLoader()); return classLoader ; }
}
代码编辑耗时 40 分钟 ;自己感觉很慢!!
文本文件,我想写个Java程序,读一遍这个 文件,然后打印出来文件中英文字母(a 到 z)出现的次数。不区分大小写。 代码: import java.io.FileInputStream; import java.io.InputStreamReader; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map;
public class LinjiawangMain { public static void main(String[] args) throws Exception { Map<Character, Integer> map = getCountByFileLetters("chars.txt") ; for(char ctmp : map.keySet()){ System.out.println( ctmp+"="+map.get(ctmp) ); } } //统计 文件字符工具方法 public static Map<Character, Integer> getCountByFileLetters(String filePath) throws Exception{ //逻辑 参数定义 int int_A = 'A'; int int_Z = 'Z'; int int_a = 'a'; int int_z = 'z'; //数据收集 map (保持存储顺序 使用 LinkedHashMap ) Map<Character, Integer> map = new LinkedHashMap<Character, Integer>(); //以 ISO-8859-1 字符 读取 .classpath 下的 文件 InputStreamReader read = new InputStreamReader(new FileInputStream( LinjiawangMain.class.getClassLoader().getResource(filePath) .getPath()), "ISO-8859-1"); //临时数据收集 int[] iis = new int[int_z-int_a]; while(read.ready() ){ int itmp = read.read(); // 当 'a'<=itmp<='z' (短路) // 当 'A'<=itmp<='Z' (非短路) 后修改itmp到 'a' 到 'z'范围 if( ( itmp >=int_a && itmp<=int_z ) || ( itmp>=int_A && itmp<=int_Z ) | (itmp=(itmp+(int_a-int_A)))>=int_a ){ iis[itmp-int_a]++ ; } } //由 临时数据收集 转 到正式收集 for(int i=0;i<int_z-int_a;i++){ map.put( (char)(i+int_a),iis[i] ); } //非修改 map return Collections.unmodifiableMap(map) ; } }
文件:aAbbbbCCCCc2345ABdb abc d
那位来开个头吧
正则匹配 html标题
<[hH]([1-9])>.*?</[hH]\1> 数据库查询执行顺序: from->where->group by->聚集函数->having->order by table level(id,name) select count(*) as cu from level where id>1 group by name desc having cu>=1 order by id ; 火狐 xpath 取 document dom 值: id('table8')/tbody/tr[6]/td/@valign 数据库有为空列排放位置: 1. select name, case when name is null then 0 else 1 end as is_null from level order by is_null ; 2.select name from level where name is null union select name from level where name is not null ; 数据库报表表链为空项替换为0table a (id); values - > 1 ,2 ,3 table b (id,num); -> (1,15),(1,5) 查询结果为 要为 1 20 2 0 3 0 select a.id as id, sum( case when b.num is null then 0 else b.num end ) as num from a left join b on a.id=b.id group by id ;
package
uu;
import
java.io.BufferedReader;
import
java.io.File;
import
java.io.FileInputStream;
import
java.io.FileOutputStream;
import
java.io.InputStreamReader;
import
java.io.OutputStreamWriter;
import
java.util.ArrayList;
import
java.util.HashMap;
import
java.util.List;
import
java.util.Map;
import
java.util.regex.Pattern;
public
class
MainExc {
//
数据文本
static
String filePath
=
"
smsservice.data
"
;
//
输出文本
static
String outfile
=
"
outfile.html
"
;
//
输出 文本格式
static
String charset
=
"
GBK
"
;
//
数据逻辑 展现
static
Map
<
Pattern, String
>
map
=
new
HashMap
<
Pattern, String
>
();
static
{ map.put(Pattern.compile(
"
^XZT
"
),
"
sina
"
);
。。。。。 }
//
类型定义
static
Map
<
Pattern, String
>
maptype
=
new
HashMap
<
Pattern, String
>
();
static
{
maptype.put(Pattern.compile(
"
^3P45
"
),
"
客户端
"
); maptype.put(Pattern.compile(
"
^6930
"
),
"
图表
"
);
......
}
//
禁止展现
static
List
<
Pattern
>
listNo
=
new
ArrayList
<
Pattern
>
();
static
{ listNo.add(Pattern.compile(
"
^9588Command$
"
)); listNo.add(Pattern.compile(
"
^5kjsCommand$
"
)); listNo.add(Pattern.compile(
"
^529901001011021$
"
)); listNo.add(Pattern.compile(
"
^529901001011022$
"
)); }
public
static
void
main(String[] args)
throws
Exception {
//
read
InputStreamReader read
=
new
InputStreamReader(
new
FileInputStream(MainExc.
class
.getClassLoader().getResource( filePath).getPath()), charset);
//
writer
if
(MainExc.
class
.getClassLoader().getResource(outfile)
==
null
) {
new
File(MainExc.
class
.getClassLoader().getResource(
"
.
"
).getPath()
+
"
/outfile.html
"
).createNewFile(); } OutputStreamWriter writer
=
new
OutputStreamWriter(
new
FileOutputStream(MainExc.
class
.getClassLoader() .getResource(outfile).getPath()), charset);
//
内存 装载 处
List
<
Map
<
String, String
>>
datas
=
new
ArrayList
<
Map
<
String, String
>>
();
StringBuffer buffer
=
new
StringBuffer(); BufferedReader reader
=
new
BufferedReader(read); String stmp
=
null
; List
<
String
>
colName
=
new
ArrayList
<
String
>
();
//
得到 列名
if
((stmp
=
reader.readLine())
!=
null
&&
!
stmp.trim().equals(
""
)) {
//
split - > Tab
for
(String stmp2 : stmp.split(
"
"
)) { colName.add(stmp2); } }
//
列数据收集
while
((stmp
=
reader.readLine())
!=
null
&&
!
stmp.trim().equals(
""
)) {
Map
<
String, String
>
data
=
new
HashMap
<
String, String
>
(); String[] sdata
=
stmp.split(
"
"
);
for
(
int
i
=
0
; i
<
colName.size(); i
++
) { data.put(colName.get(i), sdata[i]); } datas.add(data); }
//
writer
writer.append(
"
<center><table border>\n
"
); writer.append(
"
<tr>
"
+
"
<td>通道伙伴</td>
"
+
"
<td>指令</td>
"
+
"
<td>长号码</td>
"
+
"
<td>资费</td>
"
+
"
<td>业务类型(图表/客户端)</td>
"
+
"
</tr>\n
"
);
//
通道伙伴 指令 长号码 资费 业务类型(图表?客户端?)
wfor:
for
(Map
<
String, String
>
mtmp : datas) {
for
(Pattern ptmp : listNo) {
if
(ptmp.matcher(mtmp.get(
"
command
"
)).find()) {
continue
wfor; } }
String hzhb
=
""
;
for
(Pattern ptmp : map.keySet()) {
if
(ptmp.matcher(mtmp.get(
"
command
"
)).find()) { hzhb
=
map.get(ptmp); } }
String type
=
""
;
for
(Pattern ptmp : maptype.keySet()) {
if
(ptmp.matcher(mtmp.get(
"
command
"
)).find()) { type
=
maptype.get(ptmp); } }
writer.append(
"
<tr>
"
+
"
<td align='center'>
"
+
hzhb
+
"
</td>
"
+
"
<td align='center'>
"
+
mtmp.get(
"
command
"
)
+
"
</td>
"
+
"
<td align='center'>
"
+
mtmp.get(
"
num
"
)
+
"
</td>
"
+
"
<td align='center'>
"
+
mtmp.get(
"
money
"
)
+
"
</td>
"
+
"
<td align='center'>
"
+
type
+
"
</td>
"
+
"
</tr>\n
"
); } writer.append(
"
</table></center>\n
"
);
//
save
writer.flush(); writer.close(); }
}
一篇非常好的 Hibernate 文章 出自: http://guxing.blog.enorth.com.cn/article/174717.shtml Hibernate最让人头大的就是对集合的加载形式。 书看了N次了,还是没有真正理解Hibernate。所以下午专门做了下测试,对配置文件的意思加深了认识。
假设有两个表,Photos(一) --- picture(多)Photo包含picture集合
结论1: HQL代码 > fetch(配置) > lazy (配置) 结论2: 默认 lazy="true" 结论3: fetch 和 lazy 主要是用来级联查询的, 而 cascade 和 inverse 主要是用来级联插入和修改的 结论4: 如果你是用spring来帮你管理你的session, 并且是自动提交,延迟加载就等于没加载~_~(当然除非你手动重新打开session然后手动Hibernate.initialize(set);然后关闭session. 结论5: cascade主要是简化了在代码中的级联更新和删除。 j结论6:老爸可以有多个孩子,一个孩子不能有多个老爸,而且老爸说的算, 孩子围着老爸转。所以Photos老爸要有权力所以 cascade 这个关键子都是送给老爸的, 也就是级联更新,老爸改姓了,儿子也得跟着改,呵呵。“不然,就没有零花钱咯”。而Picture儿子整体挨骂,但是还是要维护父子之间良好的关系,对老爸百依百顺,所以老爸就说,儿子,“关系,由你来维护(inverse="true") ,不然就不给零花钱。呵。”。 <set name="pictures" inverse="true" cascade="all"> <key> <column name="photosid" not-null="true" /> </key> <one-to-many class="girl.domain.Picture" /> </set> 测试代码:
Photos p = ps.getById(1); Set<Picture> set = p.getPictures(); for(Picture pic : set){ System.out.println(pic.getId()); }
配置文件的一部分: <set name="pictures" inverse="true" cascade="all" > <key> <column name="photosid" not-null="true" /> </key> <one-to-many class="girl.domain.Picture" /> </set>
测试过程会对配置文件不断修改:并且从来不曾手动重新打开session
测试结构:
当配置条件为 lazy=true一句查询 测试代码中没有调用getPicture() 正常 Hibernate:
select photos0_.id as id0_0_, photos0_.userid as userid0_0_,
photos0_.typeid as typeid0_0_, photos0_.name as name0_0_,
photos0_.createtime as createtime0_0_, photos0_.description as
descript6_0_0_, photos0_.faceid as faceid0_0_, photos0_.uri as uri0_0_
from super.photos photos0_ where photos0_.id=? lazy=true 一句查询 有getPicture() Hibernate: select photos0_.id as
id0_0_, photos0_.userid as userid0_0_, photos0_.typeid as typeid0_0_,
photos0_.name as name0_0_, photos0_.createtime as createtime0_0_,
photos0_.description as descript6_0_0_, photos0_.faceid as faceid0_0_,
photos0_.uri as uri0_0_ from super.photos photos0_ where photos0_.id=? lazy=true 一句查询 有getPicture() 并且访问了里面的元数Picture 且有异常抛出 Hibernate:
select photos0_.id as id0_0_, photos0_.userid as userid0_0_,
photos0_.typeid as typeid0_0_, photos0_.name as name0_0_,
photos0_.createtime as createtime0_0_, photos0_.description as
descript6_0_0_, photos0_.faceid as faceid0_0_, photos0_.uri as uri0_0_
from super.photos photos0_ where photos0_.id=?
lazy="false" 两句查询 肯定没问题,因为全部数据都个查了出来 所以怎么调用都正常 Hibernate:
select photos0_.id as id0_0_, photos0_.userid as userid0_0_,
photos0_.typeid as typeid0_0_, photos0_.name as name0_0_,
photos0_.createtime as createtime0_0_, photos0_.description as
descript6_0_0_, photos0_.faceid as faceid0_0_, photos0_.uri as uri0_0_
from super.photos photos0_ where photos0_.id=? Hibernate: select
pictures0_.photosid as photosid1_, pictures0_.id as id1_, pictures0_.id
as id2_0_, pictures0_.photosid as photosid2_0_, pictures0_.name as
name2_0_, pictures0_.clicked as clicked2_0_, pictures0_.uploaddate as
uploaddate2_0_, pictures0_.size as size2_0_, pictures0_.description as
descript7_2_0_, pictures0_.uri as uri2_0_ from super.picture pictures0_
where pictures0_.photosid=?
fetch="join" 一句查询 效果 == lazy="false" 呵呵,哪个效率高,我就不知道了。。。。。。。。。。。 Hibernate:
select photos0_.id as id0_1_, photos0_.userid as userid0_1_,
photos0_.typeid as typeid0_1_, photos0_.name as name0_1_,
photos0_.createtime as createtime0_1_, photos0_.description as
descript6_0_1_, photos0_.faceid as faceid0_1_, photos0_.uri as uri0_1_,
pictures1_.photosid as photosid3_, pictures1_.id as id3_, pictures1_.id
as id2_0_, pictures1_.photosid as photosid2_0_, pictures1_.name as
name2_0_, pictures1_.clicked as clicked2_0_, pictures1_.uploaddate as
uploaddate2_0_, pictures1_.size as size2_0_, pictures1_.description as
descript7_2_0_, pictures1_.uri as uri2_0_ from super.photos photos0_
left outer join super.picture pictures1_ on
photos0_.id=pictures1_.photosid where photos0_.id=?
不加fetch="join"一句查询 没有getPicture() 正常 Hibernate: select
photos0_.id as id0_0_, photos0_.userid as userid0_0_, photos0_.typeid
as typeid0_0_, photos0_.name as name0_0_, photos0_.createtime as
createtime0_0_, photos0_.description as descript6_0_0_, photos0_.faceid
as faceid0_0_, photos0_.uri as uri0_0_ from super.photos photos0_ where
photos0_.id=? 不加fetch="join" 一句查询 有getPicture() 正常 Hibernate: select
photos0_.id as id0_0_, photos0_.userid as userid0_0_, photos0_.typeid
as typeid0_0_, photos0_.name as name0_0_, photos0_.createtime as
createtime0_0_, photos0_.description as descript6_0_0_, photos0_.faceid
as faceid0_0_, photos0_.uri as uri0_0_ from super.photos photos0_ where
photos0_.id=? 不加fetch="join"一句查询 有getPicture() 并且访问里面的元素Picture的ID 有异常抛出 Hibernate:
select photos0_.id as id0_0_, photos0_.userid as userid0_0_,
photos0_.typeid as typeid0_0_, photos0_.name as name0_0_,
photos0_.createtime as createtime0_0_, photos0_.description as
descript6_0_0_, photos0_.faceid as faceid0_0_, photos0_.uri as uri0_0_
from super.photos photos0_ where photos0_.id=? 来个两兵交战 fetch="join" lazy="true" 呵呵 结果,一句查询, 结构正常 所以就当lazy不存在好了。 看来fetch 是老大。、、、、、、、、、、、、、 Hibernate:
select photos0_.id as id0_1_, photos0_.userid as userid0_1_,
photos0_.typeid as typeid0_1_, photos0_.name as name0_1_,
photos0_.createtime as createtime0_1_, photos0_.description as
descript6_0_1_, photos0_.faceid as faceid0_1_, photos0_.uri as uri0_1_,
pictures1_.photosid as photosid3_, pictures1_.id as id3_, pictures1_.id
as id2_0_, pictures1_.photosid as photosid2_0_, pictures1_.name as
name2_0_, pictures1_.clicked as clicked2_0_, pictures1_.uploaddate as
uploaddate2_0_, pictures1_.size as size2_0_, pictures1_.description as
descript7_2_0_, pictures1_.uri as uri2_0_ from super.photos photos0_
left outer join super.picture pictures1_ on
photos0_.id=pictures1_.photosid where photos0_.id=?
参考引用: 使用说明: lib添加dwr.jar web.xml添加 <?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> <web-app id="dwr"> <display-name>DWR (Direct Web Remoting)</display-name> <description>A Simple Demo DWR</description>
<servlet> <servlet-name>dwr-invoker</servlet-name> <display-name>DWR Servlet</display-name> <description>Direct Web Remoter Servlet</description> <servlet-class>org.directwebremoting.servlet.DwrServlet</servlet-class>
<!-- This should NEVER be present in live --> <init-param> <param-name>debug</param-name> <param-value>true</param-value> </init-param>
</servlet> <!-- 服务起来后 在地址中直接输入 http://.../dwr 就可以查看对外提供的服务类 --> <servlet-mapping> <servlet-name>dwr-invoker</servlet-name> <url-pattern>/dwr/*</url-pattern> </servlet-mapping>
</web-app>
dwr.xml <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE dwr PUBLIC "-//GetAhead Limited//DTD Direct Web Remoting 1.0//EN" "http://www.getahead.ltd.uk/dwr/dwr10.dtd"> <dwr> <allow> <!-- 远程调用类 定义 updateItem,getItem 和 findItems 方法可用 --> <create creator="new" javascript="CatalogDAO"> <param name="class" value="com.ajaxlab.ajax.CatalogDAO" /> <include method="getItem" /> <include method="findItems" /> <include method="updateItem" /> </create> <!-- 数据展现定义格式 (javascriot json 格式) 此定义 id name description 为可见 price 隐藏 E.g -> { description:"中国制造.", id:"产品-", name:"新品-" } --> <convert converter="bean" match="com.ajaxlab.ajax.Item"> <param name="include" value="id,name,description,formatted- Price" /> </convert> </allow> </dwr>
类说明 bean Item: private String id = ""; private String name = ""; private String description = ""; private int price = 0; get();set(); dao public Item getItem(String id) { Item item = new Item("产品-"+id); item.setName("新品-"+id); item.setPrice(100); item.setDescription("中国制造."); return item; }
public List findItems(String expression) { List list = new ArrayList(); Item item1 = new Item("产品-001"); item1.setName("新品-001"); item1.setDescription(expression); item1.setPrice(10); Item item2 = new Item("产品-002"); item2.setName("新品-002"); item2.setDescription(expression); item2.setPrice(15); Item item3 = new Item("产品-003"); item3.setName("新品-003"); item3.setDescription(expression); item3.setPrice(35); list.add(item1); list.add(item2); list.add(item3); return list;
}
/* html input text -> { description:"中国制造.", id:"1", name:"刘凯毅" } return true ; */ public boolean updateItem(Item item ){ if( item!=null && item.getName().equals("刘凯毅") ) return true; return false ; }
js 方法: 在 input 输入->> method( !! )
bean(id,name...) {id:1,name:'liukaiyi'}
当多参数 为 map {dd:'liu',aa:'gg'}
js多参数 class.method( objectEval($("p00").value), objectEval($("p01").value), reply0);展现页: <html> <head> <title>DWR Test</title> <!-- These paths use .. so that they still work behind a path mapping proxy. The fully qualified version is more cut and paste friendly. --> <script type='text/javascript' src='/testDwr/dwr/interface/CatalogDAO.js'></script> <script type='text/javascript' src='/testDwr/dwr/engine.js'></script> <script type='text/javascript' src='/testDwr/dwr/util.js'></script> <script type='text/javascript'> //输入到方法中 参数 格式转换 function objectEval(text){ text = text.replace(/\n/g, ' '); text = text.replace(/\r/g, ' '); if (text.match(/^\s*\{.*\}\s*$/)) { text = '[' + text + '][0]'; } return eval(text); } //本例 alert 展现 var reply = function(data){ alert(dwr.util.toDescriptiveString(data, 2)); }
</script>
</head> <body >
<li> findItems( <input type='text' value='""' id='p00' /> ); <input class='ibutton' type='button' onclick='CatalogDAO.findItems(objectEval($("p00").value), reply);' value='Execute' />
</li> <li> getItem( <input class='itext' type='text' size='10' value='""' id='p10' title='Will be converted to: java.lang.String'/> ); <input class='ibutton' type='button' onclick='CatalogDAO.getItem(objectEval($("p10").value), reply);' value='Execute' title='Calls CatalogDAO.getItem(). View source for details.'/> </li>
<li> updateItem( <input class='itext' type='text' size='10' value='{}' id='p20'/> ); <input class='ibutton' type='button' onclick='CatalogDAO.updateItem(objectEval($("p20").value), reply);' value='Execute' /> </li>
</body></html>
摘要: 本文提供:1.企业分类数据2.此类用于吧文本 数据变成 sql 并插入数据库
Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->
import
java.io.BufferedReader;
im... 阅读全文
摘要: 直接运行demo http://www.blogjava.net/Files/Good-Game/iba2.rar
数据说明:
Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->
/*
ibatis ... 阅读全文
dome 使用hsql 数据库; 一对多,多对一; 可以直接运行的 dome:http://www.blogjava.net/Files/Good-Game/iba.rar本例指涉及到查询,为了简单没有事务,和service层 先看测试运行: @Test public void testLevel() {
try {
Level level = (Level)DaoConfig.getSqlMap().queryForObject("level.getLevelId", new Integer(2) ); System.out.println("f_level="+level.getFlevel().getName());
System.out.println("->level="+level.getName()); for(Level ltmp : level.getClevel()){ System.out.println("c_root="+ltmp.getName()); } } catch (SQLException e) { e.printStackTrace(); } } 运行结果:hsql 数据库 初始化 create table level ( id int not null, name varchar(80) null, fid int , constraint pk_supplier primary key (id), constraint fk_item_1 foreign key (fid) references level (id) ) create index levelName on level (name) insert into level (id,name,fid) values(1,'root',null) insert into level (id,name,fid) values(2,'level_1',1) insert into level (id,name,fid) values(3,'root_2',1) insert into level (id,name,fid) values(4,'root_1_1',2) insert into level (id,name,fid) values(5,'root_1_2',2) insert into level (id,name,fid) values(6,'root_1_1_1',4)
运行结果 f_level=root ->level=level_1 c_level=root_1_1 c_level=root_1_2 DaoConfig工具类:
package test.persistence;
import com.ibatis.common.jdbc.ScriptRunner; import com.ibatis.common.resources.Resources; import com.ibatis.sqlmap.client.SqlMapClient; import com.ibatis.sqlmap.client.SqlMapClientBuilder;
import java.io.IOException; import java.io.PrintWriter; import java.io.Reader; import java.sql.Connection; import java.sql.DriverManager; import java.util.Properties; /** * damo api * http://portals.apache.org/bridges/multiproject/jpetstore/apidocs/overview-summary.html * @author Administrator * */ public class DaoConfig {
private static SqlMapClient sqlMap = null ; static { try { Properties props = Resources.getResourceAsProperties("properties/database.properties"); String url = props.getProperty("url"); String driver = props.getProperty("driver"); String username = props.getProperty("username"); String password = props.getProperty("password"); if (url.equals("jdbc:hsqldb:mem:jpetstore")) { Class.forName(driver).newInstance(); Connection conn = DriverManager.getConnection(url, username, password); try { ScriptRunner runner = new ScriptRunner(conn, false, false); runner.setErrorLogWriter( new PrintWriter( System.out ) ); runner.setLogWriter(new PrintWriter( System.out )); runner.runScript(Resources.getResourceAsReader("hsql/test.sql")); }catch (Exception e) { e.printStackTrace(); } finally { conn.close(); } } String resource = "test/persistence/sql-map-config.xml"; Reader reader = Resources.getResourceAsReader (resource); sqlMap = SqlMapClientBuilder.buildSqlMapClient(reader); } catch (Exception e) { throw new RuntimeException("Description. Cause: " + e, e); } }
public static SqlMapClient getSqlMap(){ return sqlMap ; }
}
dao: public class LevelDao { public static List<Level> getAll(){ try { return DaoConfig.getSqlMap().queryForList("getAllLevel"); } catch (Exception e) { e.printStackTrace(); } return null ; } }
持久类说明package test.domain;
import java.util.List;
public class Level { private Integer id ; private String name ; //得到此对象父节点 (多对一) private Level flevel ; //得到此对象孩子节点 (一对多) private List<Level> clevel;
public Integer getId() { return id; }
public void setId(Integer id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public Level getFlevel() { return flevel; }
public void setFlevel(Level flevel) { this.flevel = flevel; }
public List<Level> getClevel() { return clevel; }
public void setClevel(List<Level> clevel) { this.clevel = clevel; }
}
level.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE sqlMap PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN" "http://ibatis.apache.org/dtd/sql-map-2.dtd">
<sqlMap namespace="level">
<typeAlias alias="level" type="test.domain.Level" /> <resultMap class="level" id="getLevelByFa"> <result property="id" column="id" /> <result property="name" column="name" /> <result property="flevel" column="fid" select="level.getLevelId"/> <result property="clevel" column="id" select="level.getLevelByfId"/> </resultMap>
<select id="getLevelId" resultClass="level" parameterClass="int" resultMap="getLevelByFa" > select id , name , fid from level WHERE id =#id# </select> <select id="getLevelByfId" resultClass="level" parameterClass="int" resultMap="getLevelByFa" > select id , name , fid from level WHERE fid =#id# </select> </sqlMap>
map confg <?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE sqlMapConfig PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN" "http://ibatis.apache.org/dtd/sql-map-config-2.dtd">
<sqlMapConfig > <properties resource="properties/database.properties"/> <settings useStatementNamespaces="true" /> <transactionManager type="JDBC"> <dataSource type="SIMPLE"> <property value="${driver}" name="JDBC.Driver"/> <property value="${url}" name="JDBC.ConnectionURL"/> <property value="${username}" name="JDBC.Username"/> <property value="${password}" name="JDBC.Password"/> </dataSource> </transactionManager>
<sqlMap resource="test/persistence/level.xml"/>
</sqlMapConfig>
html <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Insert title here</title> </head> <body> <form action=""> <table> <tr> <td> <select id="s1" size="5"> <option>-1-</option> <option>-2-</option> <option>-3-</option> </select> </td> <td> <input type="button" value=">>" onclick="optionRemove('s1','s2');"/> <input type="button" value="<<" onclick="optionRemove('s2','s1');"/> </td> <td> <select id="s2" size="5"> </select> </td> </tr> </table> </form>
</body> <script type="text/javascript"> function optionRemove(selFromById,selToById){ var sf = document.getElementById(selFromById); var st = document.getElementById(selToById); var mo = sf.options[sf.selectedIndex]; var moTest = mo.text ; var moValue = mo.value ; sf.remove(sf.selectedIndex); st.options.add(new Option(moTest,moValue ),0)
} </script> </html>
<
input
type
="hidden"
name
="SMSServices"
value
=""
/>
<
td
>
<
select
size
="5"
name
="from_SMSServices"
>
<%
for
(SMSService stmp : SMSServiceUtils.getAllSMSService()) {
%>
<
option
value
="<%=stmp.getId()%>"
>
<%
=
stmp.getName()
%>
</
option
>
<%
}
%>
</
select
>
</
td
>
<
td
>
<
input
type
="button"
value
='>>'
onclick
="optionSelectedMove(this.form,'from_SMSServices','to_SMSServices');"
/><
br
/>
<
input
type
="button"
value
='<<'
onclick
="optionSelectedMove(this.form,'to_SMSServices','from_SMSServices');"
/>
</
td
>
<
td
>
<
select
size
="5"
name
="to_SMSServices"
>
</
select
>
</
td
>
</
tr
>
<
tr
><
input
type
="button"
value
="提交"
onClick
="addSMSServicesValues('SMSServices','to_SMSServices');this.form.submit();"
/></
tr
>
javascript 方法 function addSMSServicesValues(smsName,selectName){ var obj = document.getElementsByName(smsName)[0]; var selObj = document.getElementsByName(selectName)[0]; obj.value = ''; for(var i=0;i<selObj.options.length;i++) { obj.value += selObj.options[i].value+';'; } } function optionSelectedMove(tform,selfromName,seltoName){
var selfromObj = document.getElementsByName(selfromName)[0]; var seltoObj = document.getElementsByName(seltoName)[0];
var optmp = null ; for(var i=0;i<selfromObj.options.length;i++) { if(selfromObj.options[i].selected==true) { optmp = selfromObj.options[i]; selfromObj.remove(i); break; } }
//var varItem = new Option(objItemText, objItemValue); seltoObj.options.add(optmp);
}
参考: http://www.builder.com.cn/2008/0517/866964.shtml
上面很全文就不说了。 在这logger邮件,总不成功。在此我 重写: log4j.appender.MAIL=uu.Mail #defines how often emails are send log4j.appender.MAIL.BufferSize=1 log4j.appender.MAIL.threshold=error
log4j.appender.MAIL.SMTPHost=mail.chinanet.net.cn log4j.appender.MAIL.From=wap@chinanet.net.cn log4j.appender.MAIL.To=liukaiyi@gmail.com log4j.appender.MAIL.Subject=Application.log error occurred
log4j.appender.MAIL.layout=org.apache.log4j.PatternLayout log4j.appender.MAIL.SMTPUsername=wap log4j.appender.MAIL.SMTPPassword=aaaaaa log4j.appender.MAIL.layout.ConversionPattern=%d %5p [%c] %n%m%n
package uu;
import java.util.Date; import java.util.Properties;
import javax.mail.Authenticator; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Store; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage;
import org.apache.log4j.net.SMTPAppender;
public class Mail extends SMTPAppender { public void activateOptions() { Mail sml = new Mail(); sml.send("wap","aaaaaa","liukaiyi@gmail.com","logg4j"," 邮件正文 测试开始 "); System.out.println("邮件发送成功!"); } // goMail 收邮件邮箱 mailContent 邮件正文 public static void sendMail(String goMail,String mailContent){ Mail sml = new Mail(); sml.send("wap","aaaaaa",goMail,"订单管理",mailContent); System.out.println("邮件发送成功!"); } public void send(String name,String pass,String goMail,String title,String mailContent){ try { Properties props = new Properties(); Session sendMailSession; Store store; Transport transport; props.put("mail.smtp.auth","true"); props.put("mail.smtp.host", "mail.chinanet.net.cn"); //smtp props.put("mail.smtp.user",name+"@chinanet.net.cn"); // props.put("mail.smtp.password",pass); //�ʼ���� PopupAuthenticator popA=new PopupAuthenticator();// PasswordAuthentication pop = popA.performCheck(name+"@chinanet.net.cn",pass); //��д�û������� sendMailSession = Session.getInstance(props, popA); Message newMessage = new MimeMessage(sendMailSession); newMessage.setFrom(new InternetAddress(name+"@chinanet.net.cn")); newMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(goMail)); //���շ��ʼ���ַ newMessage.setSubject(title); newMessage.setSentDate(new Date()); mailContent+="\n\n"+new Date().toLocaleString(); newMessage.setText(mailContent); //�ʼ����� transport = sendMailSession.getTransport("smtp"); transport.send(newMessage); } catch (MessagingException ex) { ex.printStackTrace(); } }
public class PopupAuthenticator extends Authenticator{ String username=null; String password=null; public PopupAuthenticator(){} public PasswordAuthentication performCheck(String user,String pass){ username = user; password = pass; return getPasswordAuthentication(); } protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } } }
此文随时更新
项目svn http://mycompetence.googlecode.com/svn/trunk/mycompetence/如在浏览器中查看有乱码问题。 请把浏览器编码改成 utf-8 或 gb2312 查看试试; 数据表结构 create.sql(未完) 项目说明 项目说明.txt(未完) 在一片声讨中,项目以蜗牛的速度慢慢开始了。 2008-6-25 尝试持久层建模; create.sql2008-6-30 16:46 添加配置工具类,并确立简单的配置插件使用 (参考:dataSource.DataSourceUtil)
项目下载地址 http://www.blogjava.net/Files/Good-Game/TurtleSwims2.rar此系统为 ssh 框架
svn : cd E:\svnProject e: start svnserve -d -r .
1.spring 管理hibernate事务
2.spring 管理struts2注入
3.ant demo 中hibernate对类文件下的使用 可在ant 中找到 <!-- hibernate 需要维护的 fileset --> <fileset dir="demo"> <include name="**/*Bean.java" /> </fileset> 生成映射 4.ant hbm2ddl 0.建立此动作文件 1.备份数据库,并重建数据库 2.建立hbm2ddl标签并建create table sql 文件 3.执行sql文件
5.ant test 可在ant 中找到<!-- junit 需要维护的 fileset --> 对类文件为 Test*.class ./conf/htmlreport/junit-noframes.html
6.web table 展现 可以使用 eXtremeComponents http://127.0.0.1:8080/TurtleSwims/demo/extremecomponents.jsp
7.在线文本编辑器 /TurtleSwims/demo/fckeditor.jsp commons-fileupload.jar FCKeditor-2.3-modify.jar
8.文件上传 fileUploadDemo.action /demo/strtus2/fileUploadDemo.jsp
9.图片生成 /demo/pictureYield.action
摘要: 功能描述:
1.ant hibernate:由class xdoclet 得到映射.2.hbm2ddl action 2.0.建立此动作文件 2.1.备份数据库,并重建数据库 2.2.建立hbm2ddl标签并建create table sql 文件 ... 阅读全文
大家有什么好意见尽量跟我说。我尽量把这编文章弄得更适应大家开发。方便大家使用 此文时时更新!1.每张表除有关业务描述列外最好预留: - IsShow(true/false) 一些关键数据删除采用隐藏.
- version(long|int) 乐观锁使用 hibernate 问题_3(锁
- 预留扩展字段 (可以参考:google protobuf 等)
2. 关联关系映射注意 21. 示例:父子关系(Parent Child Relationships)- 添加级联孩子对象,会生成两条sql(
INSERT 为c 创建,
UPDATE p 到c 的连接p)。
解决办法:<set name="children" inverse="true"> 参考: 21.2. 双向的一对多关系(Bidirectional one-to-many) 解决办法1:<set name="children" inverse="true" cascade=" all-delete-orphan"> 参考: 21.3. 级联生命周期(Cascading lifecycle) 解决办法2: 删除隐藏策略 <set name="children" inverse="true" where=" IsShow=boolean|int " cascade=" save-update"> 许多数据库没有boolean类型可以用 整型替代 数据建立默认0可见,不可见改为1. 3一般表设计
google svn 服务器使用: 1. http://code.google.com/ 用gmail登入。>后点击> Project Hosting 2. 进入>> http://code.google.com/hosting/ >后点击> Create a new project 3. 填入必要的项目名,描述等确定。就可以了 4. 确定成功后 -> Source 5. 到eclipse的打开新建一个project->team->share Project->svn 6. 后面根据 google source 上的svn提示,这我就不多说了。一般的svn http url
这些日子一直在想,将来的我怎么在技术这条道路上好好走下去(这一辈子我都会干技术的,我相信我自己)。 想着想着慢慢的开始害怕自己被淘汰。我才24岁就我工作的一年半中,就看到太多太多的技术被更替,被淘汰。又太多的新技术出现在我们面前。我这年努力去追赶(学习新技术就是一种投资^_^) 应该要有些压箱底的东西!就今天开始先学数学;后数据结构;最后算法。我要把原来大学学的一点一点捡回来了。 学习之前给自己找个数学学习工具; scilab(开源) http://www.scilab.org/ (参考) http://blog.chinaunix.net/u/7217/article_40744.html http://blog.chinaunix.net/u1/56796/showart_694786.html 与之对应的 matlab(企业)对现在我来说太大了
scilab安装后运行 在命令行写入(运行后): A=[1 2 3 4;5 6 7 8]
hist3d(A);
就用数据 数据库表地址数据(中国地区)来说吧 存储过程:DELIMITER // drop procedure if exists useCursor // create temporary table if not exists aop.tmp_table(data bigint(20))//
//建立存储过程 CREATE PROCEDURE useCursor(iid bigint(20)) BEGIN //局部变量定义 declare tid bigint(20) default -1 ; //游标定义 declare cur1 CURSOR FOR select id from aop.location where fid=iid ; //游标介绍定义 declare CONTINUE HANDLER FOR SQLSTATE '02000' SET tid = null; //开游标 OPEN cur1; FETCH cur1 INTO tid;
WHILE ( tid is not null ) DO insert into aop.tmp_table values(tid); //树形结构数据递归收集到建立的临时表中 call useCursor(tid); FETCH cur1 INTO tid ; END WHILE; END;// DELIMITER ;
//查询开始 ,运行是成功的,但用时有10多秒之多,才几百条数据; //望那个大牛 帮帮解决下时间问题! call useCursor(1); select * from tmp_table ; drop temporary table if exists aop.tmp_table ; 结果: | 187 | | 188 | | 189 | | 190 | | 191 | | 192 | | 193 | | 194 | | 195 | | 196 | | 197 | | 198 | | 199 | | 200 | | 201 | | 202 | | 203 | | 204 | | 205 | | 206 | | 207 | | 208 | | 209 | .
public
static
String filter(String input) {
if
(input
==
null
) {
return
null
; } StringReader stringReader
=
new
StringReader(input); BufferedReader reader
=
new
BufferedReader(stringReader);
StringBuffer ret
=
new
StringBuffer(input.length()
+
200
);
//
add more room to the result String
String line
=
null
;
try
{ //换行后添加<br/>
while
((line
=
reader.readLine())
!=
null
) { //wap 对 < >的替换 ret.append(line.replaceAll(
"
<
"
,
"
<
"
).replaceAll(
"
>
"
,
"
>
"
).
replaceAll(
"&", "&"
)
).append(
"
<br/>
"
); }
//
while
//
如果是最后一行
}
catch
(IOException ex) {}
return
"
"
+
ret.toString() ;
}
官方: eg:xquery使用
import org.basex.core.Commands; import org.basex.core.proc.Proc; import org.basex.data.Result; import org.basex.io.ConsoleOutput; import org.basex.query.QueryException; import org.basex.query.QueryProcessor; import org.basex.query.xquery.XQueryProcessor;
/** * This class serves an example for executing XQuery requests. */ public final class XQueryExample { /** Sample query. */ private static final String XMLFILE = XPathExample.class.getClassLoader().getSystemResource( "xx.xml" ).getPath(); private static final String QUERY = " for $x in doc('"+XMLFILE+"')//property " + " return <child>{data($x/@name)}</child>";
/** Private constructor. */ private XQueryExample() { } /** * Main method of the example class. * @param args (ignored) command-line arguments * @throws Exception exception */ public static void main(final String[] args) throws Exception {
// FIRST EXAMPLE: System.out.println("First example:");
// create standard output stream final ConsoleOutput out = new ConsoleOutput(System.out);
// Create a BaseX process final Proc proc = Proc.get(Commands.XQUERY, QUERY); // launch process if(proc.execute()) { // successful execution: print result proc.output(out); } else { // execution failed: print result proc.info(out); } out.flush(); System.out.println(); // SECOND EXAMPLE (ALTERNATIVE): System.out.println("Second example:");
// Execute XQuery request try { // create query instance final QueryProcessor xquery = new XQueryProcessor(QUERY); // execute query; no initial context set is specified (null) final Result result = xquery.query(null); // print output result.serialize(out, false); out.println(); } catch(final QueryException e) { // dump stack trace e.printStackTrace(); }
// close output stream out.close(); } }
结果:
First example: <child>connection.datasource</child> <child>dialect</child> <child>show_sql</child> <child>hibernate.cache.provider_class</child> <child>cache.use_query_cache</child>
Second example: <child>connection.datasource</child> <child>dialect</child> <child>show_sql</child> <child>hibernate.cache.provider_class</child> <child>cache.use_query_cache</child>
数据来源:xx.xml
<?xml version='1.0' encoding='utf-8'?>
<hibernate-configuration>
<session-factory>
<property name="connection.datasource">java:comp/env/jdbc/USERPORTAL1</property> <property name="dialect">org.hibernate.dialect.MySQLInnoDBDialect</property> <property name="show_sql">true</property> <property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property> <property name="cache.use_query_cache">true</property> <!-- JDBC connection pool (use the built-in) -->
</session-factory>
</hibernate-configuration>
xml 数据库使用,和XQuery使用. 环境: 1.xml数据库使用 (参考:eXist Quick Start) 2.xQuery XQuery 首页 1.测试开始: 进入:eXist-> http://demo.exist-db.org/xmldb/db/ for $x in doc("/examples2.xml")/exist:result/country
return if ($x/population_growth<-1)
then <child>{data($x/name)}</child>
else <adult>{data($x/name)}</adult> |
|
---|
parent collection: /db | - <child
>
Bosnia and Herzegovina
</
child
>
| - <adult
>
Czech Republic
</
adult
>
| - <child
>
Estonia
</
child
>
| - <child
>
Faroe Islands
</
child
>
| - <adult
>
Hungary
</
adult
>
| - <adult
>
Ireland
</
adult
>
| - <child
>
Latvia
</
child
>
| - <adult
>
Lithuania
</
adult
>
| - <child
>
Romania
</
child
>
| - <adult
>
Russia
</
adult
>
|
使用数据: http://demo.exist-db.org/xmldb/db/examples2.xml 2:自定义方法: 使用:http://demo.exist-db.org/sandbox/sandbox.xql declare function local:minPrice(){ for $x in (1 to 5) return <test>{$x}</test> };
<minPrice>{local:minPrice()}</minPrice> 结果: <minPrice><test>1</test> <test>2</test> <test>3</test> <test>4</test> <test>5</test> </minPrice>
摘要: 为方便项目使用,特留!表结构:Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/--> CREATE TABLE `location` ( `id` bigint(20) NOT NULL auto_increment, `name` varchar(50... 阅读全文
参考:第 9 章 事务管理 - Spring Framework reference 2.0.5 参考手册中文版 http://doc.javanb.com/spring-framework-reference-zh-2-0-5/ch09.html先从配置文件开始: 源码: springAop.rar需要jar <?xml version="1.0" encoding="UTF-8"?> <classpath> <classpathentry kind="src" path="java"/> <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/> <classpathentry kind="lib" path="lib/aspectjrt.jar"/> <classpathentry kind="lib" path="lib/aspectjweaver.jar"/> <classpathentry kind="lib" path="lib/spring.jar"/> <classpathentry kind="lib" path="lib/spring-sources.jar"/> <classpathentry kind="lib" path="lib/commons-logging-1.0.4.jar"/> <classpathentry kind="lib" path="lib/cglib-nodep-2.1_3.jar"/> <classpathentry kind="lib" path="lib/hibernate3.jar"/> <classpathentry kind="lib" path="lib/log4j-1.2.11.jar"/> <classpathentry kind="con" path="org.eclipse.jdt.junit.JUNIT_CONTAINER/4"/> <classpathentry kind="lib" path="lib/dom4j-1.6.1.jar"/> <classpathentry kind="lib" path="lib/commons-collections-2.1.1.jar"/> <classpathentry kind="lib" path="lib/mysql.jar"/> <classpathentry kind="lib" path="lib/jta.jar"/> <classpathentry kind="lib" path="lib/antlr-2.7.6.jar"/> <classpathentry kind="output" path="bin"/> </classpath>
spring 配置
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd">
<!-- demo start --> <import resource="demo_spring.xml" /> <!-- demo end -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"> </property> <property name="url" value="jdbc:mysql://localhost:3306/aop?characterEncoding=utf8"> </property> <property name="username" value="root"></property> <property name="password" value=""></property> </bean>
<!-- hibernate3 sessionFactory --> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <!-- 此次 为 spring 事务需要使用 dataSource ;为空事务由Hibernian自己维护 --> <property name="dataSource" ref="dataSource" /> <property name="configLocation" value="classpath:hibernate.cfg.xml" /> </bean>
<!-- 事务适配器 --> <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean>
<!-- aop 与事务联系 aopBean<->txAdvice --> <aop:config> <!-- 逻辑拦截 --> <aop:pointcut id="demoAopBean" expression="execution(* demo*.*.*(..))" /> <aop:advisor advice-ref="demoTxAdvice" pointcut-ref="demoAopBean" /> </aop:config>
<!-- 事务原子 具体方法进行什么事务 --> <tx:advice id="demoTxAdvice" transaction-manager="txManager"> <tx:attributes> <tx:method name="get*" propagation="SUPPORTS" read-only="true" rollback-for="NoProductInStockException" /> <tx:method name="save*" propagation="REQUIRED" rollback-for="NoProductInStockException" /> <tx:method name="update*" propagation="REQUIRED" rollback-for="NoProductInStockException" /> <tx:method name="remove*" propagation="REQUIRED" rollback-for="NoProductInStockException" /> <tx:method name="*" propagation="SUPPORTS" rollback-for="NoProductInStockException" /> </tx:attributes> </tx:advice>
<!-- daoCalss : extends HibernateDaoSupport implements BeanDao --> <bean id="beanDao" class="demo.springHibernate.dao.imp.BeanDaoImp"> <property name="sessionFactory"> <ref bean="sessionFactory"></ref> </property> </bean>
<bean id="helloAction" class="demo.struts2Spring.HelloWorld" scope="prototype"> <property name="bds" ref="beanDao"></property> </bean> </beans>
hibernate 配置<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory name="asdf"> <property name="hibernate.dialect">mysql</property> <property name="myeclipse.connection.profile"> com.mysql.jdbc.Driver </property> <property name="connection.url"> jdbc:mysql://localhost/aop </property> <property name="show_sql">true</property> <property name="connection.username">root</property> <property name="connection.password"></property> <property name="connection.driver_class"> com.mysql.jdbc.Driver </property> <property name="dialect"> org.hibernate.dialect.MySQLDialect </property> <mapping resource="bean/UnitBean.hbm.xml" /> </session-factory> </hibernate-configuration>
dao 类(接口) package dao.imp;
import java.util.List;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import bean.UnitBean;
import dao.BeanDao;
public class BeanDaoImp extends HibernateDaoSupport implements BeanDao{ public void addBean(UnitBean unitBean) { this.getHibernateTemplate().save(unitBean); }
public List<UnitBean> getBeanByAll() { return this.getHibernateTemplate().find(" from "+UnitBean.class.getName()); }
public void removeBean(long beanId) { this.getHibernateTemplate().delete( getHibernateTemplate().get(UnitBean.class, beanId) ); } }
Main 类 package unit;
import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext;
import dao.BeanDao; import bean.UnitBean;
public class Main { public static void main(String[] args) { ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml"); BeanDao dao = (BeanDao) ctx.getBean("beanDao"); UnitBean bean = new UnitBean(); bean.setName("xx"); bean.setPass("11"); dao.addBean(bean); for(UnitBean unitBean : dao.getBeanByAll() ){ System.out.println( unitBean.getId() ); } dao.removeBean(bean.getId()); } }
结果: Hibernate: insert into bean (name, pass) values (?, ?) Hibernate: select unitbean0_.id as id0_, unitbean0_.name as name0_, unitbean0_.pass as pass0_ from bean unitbean0_ 1 Hibernate: select unitbean0_.id as id0_0_, unitbean0_.name as name0_0_, unitbean0_.pass as pass0_0_ from bean unitbean0_ where unitbean0_.id=? Hibernate: delete from bean where id=?
我的aop 基础 spring 实际使用 (这就使用一个例子说明)
测试类以及结果:
package unit;
import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext;
import bean.HelloService;
public class Main { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext( "beans.xml"); HelloService service = (HelloService) context.getBean("helloService"); service.annotationAop(); System.out.println(); service.xmlAop(); } } 结果: annotationAop//正常方法运行 aop--AspectJ! //annotation拦截
xmlAop //正常方法运行 aop--XmlAop! //配置拦截 use jar- --aspectjrt.jar
- --aspectjweaver.jar
- --acglib-nodep-2.1_3.jar
- --commons-logging.jar
- --spring.jar
- --spring-aspects.jar
XML配置<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation= "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <!-- 测试使用类 分别由 方法 annotationAop/xmlAop --> <bean id="helloService" class="bean.HelloService"/> <!-- annotation aop 拦截 使用@Aspect @Pointcut("execution(* annotationAop(..))") @AfterReturning("mainMethod()") --> <bean id="xmlAop" class="aop.AnnotationAspectJ"/> <aop:aspectj-autoproxy/> <!-- xml aop 配置文件拦截 --> <bean id="XmlAspectJ" class="aop.XmlAspectJ"/> <aop:config> <aop:aspect ref="XmlAspectJ"> <aop:pointcut id="mainMethod" expression="execution(* xmlAop(..))"/> <aop:after-returning pointcut-ref="mainMethod" method="goXmlAop"/> </aop:aspect> </aop:config> </beans> HelloService.java
package bean;
public class HelloService { public void annotationAop() { System.out.println(" annotationAop "); } public void xmlAop(){ System.out.println(" xmlAop "); } }
AnnotationAspectJ.java
package aop;
import org.aspectj.lang.annotation.AfterReturning; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut;
@Aspect public class AnnotationAspectJ { @Pointcut("execution(* annotationAop(..))") public void mainMethod() {} @AfterReturning("mainMethod()") public void sayHello() { System.out.println("aop--AspectJ!"); } }
XmlAspectJ.java
package aop;
public class XmlAspectJ { public void goXmlAop(){ System.out.println(" aop--XmlAop! "); } }
这就不介绍了 代码上: package unit;
import java.util.regex.Matcher; import java.util.regex.Pattern;
import org.junit.Assert; import org.junit.Test;
public class RegexUnit {
@Test /** * <p>向前\向后查找</p> */ public void unit9()throws Exception{ String testStr = "http://www.google.com"; /* 一般查找 * .+(:) 查询出结果包含 : */ Pattern pattern = Pattern.compile(".+(:)"); Matcher matcher = pattern.matcher(testStr); Assert.assertTrue("错误: 查找出结果通过 .+(:) 此regex没有包含 : ", matcher.find() && matcher.group().equals("http:") ); /* 向前查找 * .+(?=:) 查询结果不包含 : */ Pattern pattern2 = Pattern.compile(".+(?=:)"); Matcher matcher2 = pattern2.matcher(testStr); Assert.assertTrue("错误: 查找出结果通过 .+(?=:) 此regex有包含 : ", matcher2.find()&& matcher2.group().equals("http")); /* 向后查找 * (?<=:).+ */ Pattern pattern3 = Pattern.compile("(?<=://).+"); Matcher matcher3 = pattern3.matcher(testStr); Assert.assertTrue("错误:查找出结果包含 http:// 不向后查询", matcher3.find()&& matcher3.group().equals("www.google.com") ); }
@Test /** 回朔应用 * 查询回朔、回朔替换、回朔大小写替换 */ public void unit8()throws Exception{ String testStr = "this is a block of of test,"+ " several words here are are " + " repeated , and and they should not be. "; Pattern pattern = Pattern.compile("[ ]+(\\w+)[ ]+\\1"); Matcher matcher = pattern.matcher(testStr); //查询结果 are are Assert.assertTrue("错误:regex 不匹配 ", matcher.find()&&matcher.group().split(" ").length>=2 ); while( matcher.find() ){ Assert.assertTrue("错误:regex 不匹配 ", matcher.group().split(" ").length>=2 ); } //替换 String testStr2s = "313-555-1234"; Pattern pattern2 = Pattern.compile("(\\d{3})(-)(\\d{3})(-)(\\d{4})"); Matcher mtmp = pattern2.matcher(testStr2s); Assert.assertTrue("错误:没有查替换", mtmp.find() && mtmp.replaceAll("($1) $3-$5").equals("(313) 555-1234") ); /*大小写替换(java 不能成功) * \E 结束 \L 或 \U转换 * \l \L 把下一个字符(串)换为小写 * \ u \U 把下一个字符(串)转换为大写 * 此中 (.*?)懒散加载 */ String testStr3 = "tt:google:xx"; Pattern pattern3 = Pattern.compile("(?<=:)(.*?)(?=:)"); Matcher matcher2 = pattern3.matcher(testStr3); if( matcher2.find()) System.out.println( matcher2.group() ) ; } }
MySQL
存取控制包含2个阶段:
- 阶段1:服务器检查是否允许你连接。
- 阶段2:假定你能连接,服务器检查你发出的每个请求。看你是否有足够的权限实施它。例如,如果你从数据库表中选择(select)行或从数据库删除表,服务器确定你对表有SELECT权限或对数据库有DROP权限。
参考 :
5.8. MySQL用户账户管理
1.权限查看 mysql> show grants for 'root'@'localhost' ; +---------------------------------------------------------------------+ | Grants for root@localhost | +---------------------------------------------------------------------+ | GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' WITH GRANT OPTION | +---------------------------------------------------------------------+ 1 row in set (0.06 sec) 2.权限设置
5.8.2. 向MySQL增加新用户账户mysql> GRANT ALL PRIVILEGES ON *.* TO 'monty'@'localhost' -> IDENTIFIED BY 'some_pass';
mysql> GRANT ALL PRIVILEGES ON *.* TO 'monty'@'%' -> IDENTIFIED BY 'some_pass' WITH GRANT OPTION;
其中两个账户有相同的用户名monty和密码some_pass。两个账户均为超级用户账户,具有完全的权限可以做任何事情。一个账户
('monty'@'localhost')只用于从本机连接时。另一个账户('monty'@'%')可用于从其它主机连接。
mysql> GRANT RELOAD,PROCESS ON *.* TO 'admin'@'localhost'; 该账户只用于从本机连接。授予了RELOAD和PROCESS管理权限。这些权限允许admin用户执行mysqladmin
reload、mysqladmin
refresh和mysqladmin
flush-xxx命令,以及mysqladmin
processlist。未授予访问数据库的权限。你可以通过GRANT语句添加此类权限。
mysql> GRANT USAGE ON *.* TO 'dummy'@'localhost';
一个账户有用户名dummy,没有密码。该账户只用于从本机连接。未授予权限。通过GRANT语句中的USAGE权限,你可以创建账户而不授予任何权限。它可以将所有全局权限设为'N'。假定你将在以后将具体权限授予该账户。
下面的例子创建 3个账户,允许它们访问专用数据库。每个账户的用户名为 custom,密码为 obscure。
mysql> GRANT SELECT,INSERT,UPDATE,DELETE,CREATE,DROP -> ON bankaccount.* -> TO 'custom'@'localhost' -> IDENTIFIED BY 'obscure';
mysql> GRANT SELECT,INSERT,UPDATE,DELETE,CREATE,DROP -> ON expenses.* -> TO 'custom'@'whitehouse.gov' -> IDENTIFIED BY 'obscure';
mysql> GRANT SELECT,INSERT,UPDATE,DELETE,CREATE,DROP -> ON customer.* -> TO 'custom'@'server.domain' -> IDENTIFIED BY 'obscure';
这3个账户可以用于:
· 第1个账户可以访问bankaccount数据库,但只能从本机访问。
· 第2个账户可以访问expenses数据库,但只能从主机whitehouse.gov访问。
· 第3个账户可以访问customer数据库,但只能从主机server.domain访问。
要想不用GRANT设置custom账户,使用INSERT语句直接修改 授权表:
5.8.3. 从MySQL删除用户账户DROP USER user;
请使用 mysql 1.5 或以上version; 测试表 level ; create table test.level (name varchar(20)); 再 insert 些数据 ; /*初始化*/ drop procedure if exists useCursor // /*建立 存储过程 create */ CREATE PROCEDURE useCursor() BEGIN /*局部变量的定义 declare*/ declare tmpName varchar(20) default '' ; declare allName varchar(255) default '' ; declare cur1 CURSOR FOR SELECT name FROM test.level ; /* mysql 不知道为什么用异常加入判断 ? * 此请参考官方文档 20.2.11.
光标 光标 * 这把 游标 异常后 捕捉 * 并设置 循环使用 变量 tmpname 为 null 跳出循环。 */ declare CONTINUE HANDLER FOR SQLSTATE '02000' SET tmpname = null; /*开游标*/ OPEN cur1; /*游标向下走一步*/ FETCH cur1 INTO tmpName; /* 循环体 这很明显 把游标查询出的 name 都加起并用 ; 号隔开 */ WHILE ( tmpname is not null) DO set tmpName = CONCAT(tmpName ,";") ; set allName = CONCAT(allName ,tmpName) ; /*游标向下走一步*/ FETCH cur1 INTO tmpName; END WHILE; CLOSE cur1; select allName ; END;// call useCursor()// 运行结果: mysql> call useCursor()// +--------------------------------------+ | allName | +--------------------------------------+ | f1;c3;c6;c5;c2;c4;c1;f1;f3;f4;f2;f5; | +--------------------------------------+ 1 row in set (0.00 sec)
摘要: level 类:Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->package hbm;import java.util.Set;/** * @hibernate.class table = "level" * where = " visible = ... 阅读全文
你可以参考: 快速修改 xdoclet samples ant -build.xml 适应实际开发此文档为上面的改进版。 1.在 你电脑上建一个 ant第三方扩展文件夹,我这为:D:\ant\lib 2.当使用 eclipse->window->proferences..->ant->Runtime->Global Entries->Add External JARs->选择你建的 ant_lib 下的全部jar; 3.并在Global Entries下加入你的 classpath 使用现成的 xdoclet ant -> 加入自己的 -> <target name="hbm2ddl" depends="prepare"> <mkdir dir="${hbm2ddl.sql.dir}" /> <taskdef name="hbm2ddl" classname="org.hibernate.tool.ant.HibernateToolTask" > </taskdef> <hbm2ddl destdir="${hbm2ddl.sql.dir}" > <configuration configurationfile="../src/hibernate.cfg.xml" /> <hbm2ddl export="true" console="false" create="false" update="false" drop="false" outputfilename="bestunix.sql"/> </hbm2ddl> <!-- 支持 1.5 泛型请 搜索到xjavadoc最新1.5版本,下载,替换原来的xjavadoc-1.1.x,再次运行xdoclet任务,执行成功! --> </target>
<target name="sql" depends="hbm2ddl"> <sql driver="org.gjt.mm.mysql.Driver" password="" userid="root" autocommit="true" url="jdbc:mysql://localhost:3306/zhongqi?characterEncoding=gbk" src="../sql/data.sql" print="yes" output="sql_out.txt"> </sql> </target> 成功后就可以: 使用 xdoclet 面向对象建表 ; 通过 ant -> java2hbn, hbn2ddl,insertSql 在开发过程中当要加 jar 方法为: 1.在 ant_lib 中加入 jar 2.eclipse ->> Global Entries->Add External JARs-> 工程转换修改 Global Entries中的classpath 例: java package hbm;
import java.util.Set;
/** * @hibernate.class table = "level" * where = " visible = 0 " * @author Administrator * */ public class Level { private long id ; private String name ; private Level father ; private Set<Level> childSet ; private int visible ;
public Level(){} public Level(String name){ this.name = name ; } public Level(String name,int visible){this.visible = visible; this.name = name ; } /** * @hibernate.id generator-class = "identity" * @return */ public long getId() { return id; } public void setId(long id) { this.id = id; } /** * @hibernate.property * length = "20" * @return */ public String getName() { return name; } public void setName(String name) { this.name = name; } /** * @hibernate.many-to-one * cascade = "save-update" * inverse = "false" * column = "fid" * @return */ public Level getFather() { return father; } public void setFather(Level father) { this.father = father; } /** * @hibernate.set * lazy = "true" * table = "Level" * cascade = "save-update" * where = " visible = 0 " * @hibernate.collection-key column = "fid" * @hibernate.collection-one-to-many class = "hbm.Level" * @return */ public Set<Level> getChildSet() { return childSet; } public void setChildSet(Set<Level> childSet) { this.childSet = childSet; } /** * @hibernate.property * @return */ public int getVisible() { return visible; } public void setVisible(int visible) { this.visible = visible; } }
unit package test;
import java.util.HashSet; import java.util.List; import java.util.Set;
import hbm.Level;
import org.hibernate.Hibernate; import org.hibernate.Session; import org.hibernate.Transaction; import org.junit.Test;
import unit.HibernateUtil;
public class HbnUnit { @Test public void level() throws Exception { Session session = HibernateUtil.currentSession(); Transaction tr = session.beginTransaction(); Level level = new Level(); level.setName("f1"); Set<Level> set = new HashSet<Level>(); set.add(new Level("c1")); set.add(new Level("c2",1)); set.add(new Level("c3")); set.add(new Level("c4",1 )); set.add(new Level("c5" )); set.add(new Level("c6",1 )); level.setChildSet(set); session.save(level); session.flush() ; session.clear(); tr.commit();
} @Test public void sAll() throws Exception { Session session = HibernateUtil.currentSession(); System.out.println("---------------------------------------------"); List<Level> list = session.createQuery(" from Level tl where tl.father is null ").list(); for( Level tmp : list ){ System.out.println("---->" + tmp.getName()+" visible="+tmp.getVisible() ); for( Level tt : tmp.getChildSet() ){ System.out.println( tt.getName()+" visible="+tt.getVisible() ); } } System.out.println( list.get(0).getVisible()+":"+ list.size() ); } }
结果: Hibernate: insert into level (name, fid, visible) values (?, ?, ?) Hibernate: insert into level (name, fid, visible) values (?, ?, ?) Hibernate: insert into level (name, fid, visible) values (?, ?, ?) Hibernate: insert into level (name, fid, visible) values (?, ?, ?) Hibernate: insert into level (name, fid, visible) values (?, ?, ?) Hibernate: insert into level (name, fid, visible) values (?, ?, ?) Hibernate: insert into level (name, fid, visible) values (?, ?, ?) Hibernate: update level set fid=? where id=? Hibernate: update level set fid=? where id=? Hibernate: update level set fid=? where id=? Hibernate: update level set fid=? where id=? Hibernate: update level set fid=? where id=? Hibernate: update level set fid=? where id=? --------------------------------------------- Hibernate: select level0_.id as id0_, level0_.name as name0_, level0_.fid as fid0_, level0_.visible as visible0_ from level level0_ where ( level0_.visible = 0 ) and (level0_.fid is null) ---->f1 visible=0 Hibernate: select childset0_.fid as fid1_, childset0_.id as id1_, childset0_.id as id0_0_, childset0_.name as name0_0_, childset0_.fid as fid0_0_, childset0_.visible as visible0_0_ from level childset0_ where ( childset0_.visible = 0 ) and childset0_.fid=? c1 visible=0 c5 visible=0 c3 visible=0 0:1
此代码可以直接使用 <body> <a id='pi' href="" value="text"> text </a> <div id='div1'/> </body> <script type="text/javascript">
function showByEvent(ev,divId){ //取得各浏览器 event ev = ev || window.event; //div var useDiv = document.getElementById(divId); useDiv.style.position="absolute"; if( useDiv.style.left=="" )useDiv.style.left = "50"; if( useDiv.style.top=="" )useDiv.style.top = "10"; if( useDiv.style.zIndex=="" )useDiv.style.zIndex = "1000"; if( useDiv.style.padding=="" )useDiv.style.padding = "0px"; if( useDiv.style.backgroundColor=="" )useDiv.style.backgroundColor = "#FFFFCC"; if( useDiv.style.color=="" )useDiv.style.color = "#201000"; if( useDiv.style.fontSize=="" )useDiv.style.fontSize = "12px"; if( useDiv.style.border=="" )useDiv.style.border ="1px solid #284860"; //得到处发事件的源element var actionBean = null ; if( ev.srcElement ){ actionBean = ev.srcElement }else{ actionBean = ev.target; } //处发事件 useDiv.onmousemove = function(){ useDiv.style.visibility = ""; } useDiv.onmouseout = function(){ useDiv.style.visibility = "hidden"; } actionBean.onmouseout = function mouseOut(ev){ useDiv.style.visibility = "hidden"; } //div 定位 useDiv.style.left = actionBean.offsetTop+15 ; useDiv.style.top = actionBean.offsetLeft+15; //返回类型为 div 显示的 x , y 和 target 处发源项 和 div return { y: actionBean.offsetTop+15 , x: actionBean.offsetLeft+15 , target:actionBean, div:useDiv } }
//事件添加 document.getElementById('pi').onmousemove = function(ev){ var sbv = showByEvent(ev,"div1"); var bean = sbv.target ; var dd = sbv.div; dd.style.visibility = ""; dd.innerHTML = "<a href=http://www.baidu.com>删除"+bean.value+"</a><br>"+ "<a href=http://www.google.com>详细 by Id "+bean.id+"</a>";
};
</script>
js 上 限制:<input type="text" size="4" value="10" name="fileSizeLimit" id="fileSizeLimit"/> K <input type="file" name="file1" id="file1" size="40" onchange="changeSrc(this)"/> <br> <img src=http://blog.xunuo.com/blog/images/icons/23.gif id="fileChecker" alt="test"/>
<script type="text/javascript"> var oFileChecker = document.getElementById("fileChecker");
function changeSrc(filePicker) { oFileChecker.src = filePicker.value; }
oFileChecker.onreadystatechange = function () { if (oFileChecker.readyState == "complete") { checkSize(); } }
function checkSize() { var limit = document.getElementById("fileSizeLimit").value * 1024;
if (oFileChecker.fileSize > limit) { alert("too large"); } else { alert("ok"); } } </script> IE <html> <input type="file" name="file1" onchange="ShowSize(this.value)"> <script language="JavaScript"> <!-- function ShowSize(files) { var fso,f; fso=new ActiveXObject("Scripting.FileSystemObject"); f=fso.GetFile(files); alert( (f.size/(1024*1024))+" Bytes"); } //--> </script> </html>
参考 : http://www.codebit.cn/pub/html/javascript/tip/mouse_position/<script type="text/javascript">
function mousePosition(ev){ //支持 火狐 if(ev.pageX || ev.pageY){ return {x:ev.pageX, y:ev.pageY}; } //支持IE return { x:ev.clientX + document.body.scrollLeft - document.body.clientLeft, y:ev.clientY + document.body.scrollTop - document.body.clientTop }; }
function mouseMove(ev){ ev = ev || window.event; var mousePos = mousePosition(ev); document.getElementById('div1').innerHTML = mousePos.x +":"+mousePos.y ; document.getElementById('div1').style.left = mousePos.x+10; document.getElementById('div1').style.top = mousePos.y+50; }
//事件添加 document.onmousemove = mouseMove;
</script> <body> <p id='pi'></p> <div id='div1' style="position:absolute; left:50; top:10; z-index:1000; padding:0px; background-color:#FFFFCC; color:#201000; font-size:12px; border:1px solid #284860;"></div> </body> 直接运行
权限设计的探讨阅读后感
文章路径:http://www.chinaitpower.com/A200508/2005-08-07/183934.html
权限设计通常包括数据库设计、应用程序接口(API)设计、程序实现三个部分。
权限分类:
首先是针对数据存取的权限,通常有录入、浏览、修改、删除四种。
其次是功能,它可以包括例如统计等所有非直接数据存取操作,另外,我们还可能对一些关键数据表某些字段的存取进行限制。
权限表及相关内容大体可以用六个表来描述,如下: 1 拥有权限角色(即用户组):具体拥有权限描述实体。
2 用户表:用户的描述,其它(如地址、电话等信息); 3 角色-用户对应表:该表记录用户与角色之间的对应关系(多对多关系),一个用户可以隶属于多个角色,一个角色组也可拥有多个用户。
4 权限列表:程序所有权限列表。该表记录所有要加以控制的权限,如录入、修改、删除、执行等; 5 权限-角色-用户对应表:权限对应角色(多对多关系)再由4表关系到用户。
在探讨文中的第4条,我怎么都不太理解?望大家探讨。反向权限吗?那怎么和系统中的拥有一起描述?
下面提出一些自己的见解:
1 用户表:用户的描述,其它(如地址、电话等信息);
2 权限列表:程序所有权限列表。该表记录所有要加以控制的权限,如录入、修改、删除、执行等; 3 权限树(模糊看成角色,但有些不同。树性结构,结构数据库中表外键自己):孩子接点继承父亲接点全部权限,并在次上扩充和删减权限建立自己分支。
4 权限列表-权限树:(多对多关系)用于描述此权限树接点对父亲接点权限继承下,由自己添加和消减的权限;
本表中用一列枚举列用于表示本纪录是添加或删减权限。
5 用户-权限树:权限树接点对应用户(多对一)关系。
感觉自己的这种框架,能很好的扩充(在某接点下增,删某权限或直接找到最向近的一个权限树接点并继承)
大家多说说自己的见解,和对比下这两个框架的一些优缺点把。本人随时恭听。G_G
google doc 原稿: http://docs.google.com/Doc?id=dkvfctc_16hgvfkbfs
问题描述:实体类答案从属于实体类问题。(一对多) 效果-》 /** * 添加 问题 和 选项 * @throws Exception */@Test public void testQu() throws Exception { Session session = HibernateUtil.currentSession(); Transaction tr = session.beginTransaction(); //级联添加 Set options = new HashSet(); Options op1 = new Options(); op1.setName("op1"); options.add(op1); Options op2 = new Options(); op2.setName("op2"); options.add(op2); Options op3 = new Options(); op3.setName("op3"); options.add(op3); Problems problems = new Problems(); problems.setName("problem_1"); problems.setOptions(options); problems.setTdesc("tdesc"); problems.setType(1); Long ll = (Long)session.save(problems); System.out.println(ll); tr.commit(); mysql> select * from options ; +----+------------+--------+------+---------+ | id | problemsid | answer | name | visible | +----+------------+--------+------+---------+ | 1 | 1 | NULL | op2 | 0 | | 2 | 1 | NULL | op3 | 0 | | 3 | 1 | NULL | op1 | 0 | +----+------------+--------+------+---------+ 3 rows in set (0.00 sec)
mysql> select * from problems ; +----+-----------+------+-------+------------+---------+ | id | name | type | tdesc | questionid | visible | +----+-----------+------+-------+------------+---------+ | 1 | problem_1 | 1 | tdesc | NULL | 0 | +----+-----------+------+-------+------------+---------+ 1 row in set (0.00 sec)
//级联删除 tr.begin(); session.delete( session.get(Problems.class,ll) ); tr.commit();
mysql> select * from problems ; Empty set (0.00 sec)
mysql> select * from options ; Empty set (0.00 sec)
HibernateUtil.closeSession(); } Options类 ....... /** * @hibernate.many-to-one * cascade = "save-update" * column = "Problemsid" * class = "com.zhongqi.domain.Problems" * @return */ public Problems getProblems() { return problems; } ............
Problems 类
/** * @hibernate.set * cascade="all-delete-orphan" * inverse = "false" * lazy = "true" * @hibernate.collection-key column = "problemsid" * @hibernate.collection-one-to-many class = "com.zhongqi.domain.Options" * @return */ public Set getOptions() { return options; }
上一个blog中 粗略的使用了下 分页标签使用 pg使用问题还是有很多 如 分页中乱码、多java代码块 下面用一个 <jsp:include >来解决这些问题。 <!-- 使用写好的分页jsp 当中需要参数为 count 总结果个数 / maxPageItems(可选默认10)页面显示行数 / goUrl (可选默认本页) 跳转路径 / params request中参数 应为乱码问题 传给下一个页面 需要使用URLDecoder.decode(...) 如:String productName = URLDecoder.decode( request.getParameter("productName")==null?"":request.getParameter("productName"),"utf8" ); --> <jsp:include page="../jspUtil/page.jsp"> <jsp:param name="count" value="<%=OrderServiceImp.getOrdersCount(beginTime,endTime,userName,companyName,productName,null,zq)%>" /> <jsp:param name="maxPageItems" value="10" /> <jsp:param name="goUrl" value="/zhongqi/seleProduct.do" /> <jsp:param name="params" value="beginTime" /> <jsp:param name="params" value="endTime" /> <jsp:param name="params" value="userName" /> <jsp:param name="params" value="companyName"/> <jsp:param name="params" value="productName" /> </jsp:include> page.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@page import="java.net.URLEncoder"%> <%@page import="java.net.URLDecoder"%> <%@ taglib prefix="pg" uri="/WEB-INF/pager-taglib.tld" %>
<% int count = Integer.parseInt( request.getParameter("count") ); int maxPageItems = Integer.parseInt( request.getParameter("maxPageItems")==null?"10":request.getParameter("maxPageItems") ); //参数设置 <jsp:param name="params" value="xx" /> String[] params = (String[])request.getParameterMap().get("params"); String goUrl = request.getParameter("goUrl"); %> <div id="bgee"> <div align="center"> <pg:pager id="pager" url="<%=goUrl%>" items='<%=count%>' maxPageItems="<%=maxPageItems %>" export="offset,currentPageNumber=pageNumber" isOffset="false" scope="request"> <% for( String str : params ) { if (request.getParameter(str) != null && !request.getParameter(str).equals("")) {%> <pg:param name="<%=str %>" value='<%= URLEncoder.encode( URLDecoder.decode(request.getParameter(str),"utf-8"),"utf-8")%>'/> <% } }%>
<pg:index> <pg:prev ifnull="true"> <span> <% if (pageUrl != null) { %> <A HREF="<%= pageUrl %>">< 上一页</A> <% } %> </span> </pg:prev>
<pg:pages export="pageUrl, pageNumber"> <% if (pageNumber == currentPageNumber) { %> <span><%= pageNumber %></span> <%} else {%> <a href='<%=pageUrl%>'><%= pageNumber %></a> <%}%> </pg:pages> <pg:next ifnull="true"> <% if (pageUrl != null) { %> <a href='<%=pageUrl%>'>下一页 ></a> <%}%> </pg:next> </pg:index> </pg:pager> </div> </div>
目的:马上使用使用 xdoclet hibernate 使用: xdoclet 2 -> all jar -> build.xml;build-dist.properties;maven.xml;project.properties;project.xml 开始: 1.在项目工程 根目录下建一文件夹:xdoclet 拷贝 *.xml 到此文件下 2.在此目录下建 lib 并把 xdoclet jar 放入 . 3.修改 build.xml <!-- clean 改为 --> <target name="clean"> <delete > <fileset dir="${samples.dist.dir}" > <include name="**/*.hbm.xml"/> </fileset> </delete> </target>
<!-- hibernatedoclet 改为 version 3.0 和 include **/*.java--> <hibernatedoclet > <fileset dir="${samples.java.dir}"> <include name="**/*.java"/> </fileset> <hibernate version="3.0"/> hbm2ddl>> http://blog.csdn.net/f1musicc/archive/2006/02/21/604699.aspx eclipse->> ant runtime home + classpath = 到本工程中的 classpath ant runtime home + mysql jar ; ant runtime home + commons-collection.jar
<target name="hbm2ddl"> <mkdir dir="${hbm2ddl.sql.dir}" /> <taskdef name="hbm2ddl" classname="org.hibernate.tool.ant.HibernateToolTask" classpath="E:\\test\\caijing\\WebRoot\\WEB-INF\\classes"/> <hbm2ddl destdir="${hbm2ddl.sql.dir}"> <configuration configurationfile="../src/hibernate.cfg.xml" /> <hbm2ddl export="true" console="false" create="true" update="false" drop="false" outputfilename="bestunix.sql"/> </hbm2ddl> </target> ->target->name=hibernate->hibernate version=3.0 4.修改 build-dist.properties-> samples.lib.dir(指定工程jar) samples.src.dir/samples.java.dir(代码所在) samples.gen-src.dir (映射生成地址) samples.dist.dir = ..\\src\\java\\questionnaire samples.lib.dir = ..\\lib samples.src.dir = ..\\src\\java\\questionnaire samples.java.dir = ..\\src\\java\\questionnaire samples.gen-src.dir = ..\\src\\java\\questionnaire 加载到 eclipse 的 ant 中 调用这个 target 动起来了就这样。工作吧!
参考: http://lijunjie.javaeye.com/blog/160977目的:方便部署文件,不再使用ssh的拷贝和粘贴。 使用: ant 使用jar 包 jakarta-oro-2.0.1.jar; http://archive.apache.org/dist/jakarta/oro/ commons-net-1.4.1.jarhttp: http://apache.mirror.phpchina.com/commons/net/binaries/加载到 eclipes ant 路径上;Window→ Preferences→ Ant→ Runtime+jar build -> copy action <?xml version="1.0"?> <project> <target name="init"> <ftp server="xxx.xxx.xxx.xxx" userid="name" password="pass" remotedir="/usr/" action="get" > <fileset dir="D:\\ant\\ftp_data"> </fileset> </ftp> </target> </project> 本例小结: 时间有限,这里就展现写这些。 代码的部署方便了。 听说 sftp 服务器可以用 需要lib http://www.jcraft.com/jsch/index.html <scp trust="true" file="./src/Main.java" todir="root:pass@***.***.***.***:/tmp" /> <sshexec .....>远程运行命令!!! 还可以参考 命令 rsync http://www.oreilly.com.cn/samplechap/linuxserverhacks/ch38.pdf 有时间 再尝试
XDoclet 2 all XDoclet -> http://xdoclet.sourceforge.net/xdoclet/install.html jar 下载: http://xdoclet.codehaus.org eclipes 插件 xdoclet http://www.beust.com/doclipse/
XDoclet 1 一些工具 http://xdoclet.sourceforge.net/xdoclet/tools.html
网上demo资料: http://www.blogjava.net/martinx/archive/2006/01/25/29197.htmlXDoclet 2 for Hibernate 3 http://www.hibernate.org/338.html http://www.blogjava.net/martinx/archive/2006/01/25/29197.htmlXDoclet 2 Tags 说明 http://xdoclet.codehaus.org/XDoclet+PluginsXDoclet 1、2 对比 http://bbmyth.javaeye.com/blog/31812
大家一起,XDoclet 2时代就要来到。我们大家一起跟上。
页面分框 如: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <link href="/zhongqi/Style/Style.css" rel="stylesheet" type="text/css"> <title>无标题文档</title>
</head> <frameset rows="110,*" cols="*" frameborder="yes" border="0" bordercolor="#1e8bc1" framespacing="0" > <frame src="top.jsp" name="topFrame" scrolling="No" noresize="noresize" id="topFrame" title="topFrame" /> <frameset cols="180,*" frameborder="no" border="0" bordercolor="#1e8bc1" framespacing="1" > <frame src="left.jsp" name="leftFrame" scrolling="no" noresize="noresize" id="leftFrame" title="leftFrame" /> <frame src="main.jsp" name="mainFrame" id="mainFrame" title="mainFrame" /> </frameset> </frameset> <noframes><body> </body> </noframes></html>
其他页链接上 <a href="/zhongqi/zhongqi/huifu.jsp" target="mainFrame">回复</a>
使用标签 这是以 get 提交 <%@ taglib uri="http://jsptags.com/tags/navigation/pager" prefix="pg" %>
<div align="center" id="bgee"> <pg:pager id="pager" url='bonusdetailaction.do' items='<%=max%>' maxPageItems='10' export="offset,currentPageNumber=pageNumber" isOffset="false" scope="request"> <pg:index> <pg:prev> <a href="<%= response.encodeURL(pageUrl.replaceAll("&", "&")) %>&method=paginationEnquiries&rId=<%=request.getAttribute("rId") %>">[上一页]</a></pg:prev> <pg:pages export="pageUrl, pageNumber"> <% if (pageNumber == currentPageNumber) { %> <b><%= pageNumber %></b> <% } else { %> <a href="<%= response.encodeURL(pageUrl.replaceAll("&", "&")) %>&method=paginationEnquiries&rId=<%=request.getAttribute("rId") %>"><%= pageNumber %></a> <% } %> </pg:pages> <pg:next><a href="<%= response.encodeURL(pageUrl.replaceAll("&", "&")) %>&method=paginationEnquiries&rId=<%=request.getAttribute("rId") %>">[下一页]</a></pg:next> </pg:index> </pg:pager> </div> action int startNum = getParam(request, "pageroffset", 0); int itms = getParam(request, "maxPageItems", 10);
dao Query qu = session.createQuery(hql).setLong("rid", rw.getId()); qu.setFirstResult(start); qu.setMaxResults(itms );
数据扒出效果 双色球(2008001)=02,04,07,09,14,29#03 双色球(2008002)=03,04,18,22,25,29#09 ..
junit代码 package test;
import java.io.InputStream; import java.net.URL; import java.net.URLConnection; import java.util.regex.Matcher; import java.util.regex.Pattern;
import junit.framework.TestCase;
public class HttpConn extends TestCase { public void testT() throws Exception { zq : for(int i=2008001;true;i++){ String num = getQihao(i) ; System.out.println("双色球("+i+")="+ num); if(num==null||num.equals("")) break zq; } } public String getQihao(int qihao) throws Exception { URL url = new URL("http://www.cnlot.net/ssq/details.php?issue="+qihao); URLConnection uconn = url.openConnection(); String num = ""; InputStream in = uconn.getInputStream(); byte[] bs = new byte[in.available()]; in.read(bs); String date = new String(bs) ; Pattern pa = Pattern.compile(" .+color=red>([0-9][0-9])<.+" ); Matcher m = pa.matcher(date); while( m.find() ) num+= m.group(1)+","; pa = Pattern.compile(" .+color=blue>([0-9][0-9])<.+" ); m = pa.matcher(date); while( m.find() ) num = num.substring( 0,num.length()-1 )+"#"+m.group(1) ; pa = Pattern.compile("^(([0-9][0-9],){5,}[0-9][0-9]#([0-9][0-9],)*[0-9][0-9]\\|)*(([0-9][0-9],){5,}[0-9][0-9]#([0-9][0-9],)*[0-9][0-9])*$"); m = pa.matcher(num); if( m.find() ) return num ; else return null ; } }
httpUnit package httpUnit;
import com.meterware.httpunit.GetMethodWebRequest; import com.meterware.httpunit.WebConversation; import com.meterware.httpunit.WebForm; import com.meterware.httpunit.WebRequest; import com.meterware.httpunit.WebResponse;
import junit.framework.TestCase;
public class HttpTest extends TestCase { public void testT() throws Exception { WebConversation wc = new WebConversation(); WebRequest req = new GetMethodWebRequest( "http://www.baidu.com" ); WebResponse resp = wc.getResponse( req ); //<input type=submit value=百度一下 id=sb> //<input type=text name=wd id=kw size=36 maxlength=100> WebForm form = resp.getForms()[0]; // select the first form in the page form.setParameter( "wd", "Italian" ); resp.getForms()[0].getSubmitButtonWithID("sb").click();
System.out.println( wc.getCurrentPage().getText() ); } }
使用:pager-taglib-2.0 官方:http://jsptags.com/tags/navigation/pager 使用页面: <%@ taglib prefix="pg" uri="/WEB-INF/pager-taglib.tld" %> <%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%> <% 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 'pg.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"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> <%! private static final String getParam(ServletRequest request, String name, String defval) { String param = request.getParameter(name); return (param != null ? param : defval); }
private static final int getParam(ServletRequest request, String name, int defval) { String param = request.getParameter(name); int value = defval; if (param != null) { try { value = Integer.parseInt(param); } catch (NumberFormatException ignore) { } } return value; } %><% String style = getParam(request,"style", "simple"); String position = getParam(request, "position", "top"); String index = getParam(request, "index", "center"); int maxPageItems = getParam(request, "maxPageItems", 10); int maxIndexPages = getParam(request, "maxIndexPages", 10); List list = new ArrayList(); for(int i=0;i<1000;i++){ list.add(i); } %> </head> <body> <form action="<%= request.getRequestURI() %>" method="get"> <center> <pg:pager items="<%= list.size() %>" index="<%= index %>" maxPageItems="<%= maxPageItems %>" maxIndexPages="<%= maxIndexPages %>" isOffset="<%= true %>" export="offset,currentPageNumber=pageNumber" scope="request">
<pg:index> <!-- 引用标签页面 --> <jsp:include page="../jsp/texticon.jsp" flush="true"/> </pg:index>
/////////////////////////////////////////////////////////////////////////////////////////////////////////////// <hr> <table width="90%" cellspacing="4" cellpadding="4"> <!-- 这里参数 l为结尾数 i->offset.intValue() 起点数 --> <%for (int i = offset.intValue(), l = Math.min(i + maxPageItems, list.size()); i < l; i++) {%> <pg:item> <tr> <th> <font color="<%= list.get(i) %>"><%= i + 1 %></font> </th> </tr> </pg:item> <%}%> </table> <hr>
</pg:pager>
</body> </html>
定义分页标签样式页: <%@ page session="false" %> <%@ taglib uri="http://jsptags.com/tags/navigation/pager" prefix="pg" %> <jsp:useBean id="currentPageNumber" type="java.lang.Integer" scope="request"/> <font face="fixed"> <pg:first export="firstPageUrl=pageUrl" unless="current"> <a href="<%= firstPageUrl %>">|<</a> </pg:first> <pg:skip export="skipBackPageUrl=pageUrl" pages="<%= -10 %>"> <a href="<%= skipBackPageUrl %>"><<<</a> </pg:skip> <pg:prev export="prevPageUrl=pageUrl"> <a href="<%= prevPageUrl %>"><<</a> </pg:prev> <pg:pages><% if (pageNumber == currentPageNumber) { %> <b><%= pageNumber %></b> <% } else { %> <a href="<%= pageUrl %>"><%= pageNumber %></a> <% } %></pg:pages> <pg:next export="nextPageUrl=pageUrl"> <a href="<%= nextPageUrl %>">>></a> </pg:next> <pg:skip export="skipForwardPageUrl=pageUrl" pages="<%= 10 %>"> <a href="<%= skipForwardPageUrl %>">>>></a> </pg:skip> <pg:last export="lastPageUrl=pageUrl" unless="current"> <a href="<%= lastPageUrl %>">>|</a> </pg:last> </font>
1.数据库 mysql> desc lotteryinformation ; +-------------+--------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-------------+--------------+------+-----+---------+-------+ | id | int(11) | NO | PRI | NULL | | | type | varchar(255) | NO | | NULL | | | title | varchar(255) | YES | | NULL | | | inputTime | datetime | YES | | NULL | | | content | blob | YES | | NULL | | | recommended | bit(1) | YES | | NULL | | | categories | varchar(255) | YES | | NULL | | +-------------+--------------+------+-----+---------+-------+ 2.代码 //插入 Session sess = HibernateSessionFactory.getSession(); Transaction tr = sess.beginTransaction(); LotteryNew nn = new LotteryNew(); nn.setInputTime(new Date()); nn.setCategories("t"); nn.setTitle("new"); nn.setRecommended(true); Blob bo = Hibernate.createBlob("ggggg".getBytes()); nn.setContent(bo); sess.save(nn); tr.commit(); HibernateSessionFactory.closeSession(); //修改 sess = HibernateSessionFactory.getSession(); tr = sess.beginTransaction(); LotteryNew lo = (LotteryNew) sess.get(LotteryNew.class, nn.getId()); Blob bog = Hibernate.createBlob("xxxxx".getBytes()); lo.setContent(bog); tr.commit(); HibernateSessionFactory.closeSession(); //查找 sess = HibernateSessionFactory.getSession(); LotteryNew lo2 = (LotteryNew) sess.get(LotteryNew.class, lo.getId()); InputStream in = lo2.getContent().getBinaryStream() ; byte[] bbr = new byte[in.available()]; in.read(bbr); System.out.println(new String(bbr)); HibernateSessionFactory.closeSession();
引用:http://bbs.mysql.cn/thread-9135-1-2.html 引用: 21. 触发程序delimiter // create trigger a_bi before insert on a for each row Begin if new.s2=0 then if(new.s3=1) then insert into b(s2) values(new.s1); elseif(new.s3=2)then insert into c(s2) values(new.s1); end if; end if; end;// delimiter ;
讨厌(370801149) 14:02:04
☆づ(18246131) 14:02:45
web.xml,server.xml
讨厌(370801149) 14:02:57
server.xml
☆づ(18246131) 14:02:58
这两个地方,你都配置了吗?
讨厌(370801149) 14:03:01
en
讨厌(370801149) 14:03:14
jdbc icijavax.sql.DataSourceContainer
讨厌(370801149) 14:03:17
web.xml
讨厌(370801149) 14:03:28
WEB-INF/web.xml
讨厌(370801149) 14:03:33
context.xml
1。存储过程实现: 引用: 20.2.1. CREATE
PROCEDURE和CREATE FUNCTION(mysql在线文档)
--test.sql
DELIMITER $$ drop procedure if exists test.sproc $$ create procedure sproc(out param1 int) begin select count(*) into param1 from account; end $$ DELIMITER ; 命令 cmd-> mysql -u root test<c:\test.sql
使用: mysql> call sproc(@a); Query OK, 0 rows affected (0.00 sec)
mysql> select @a ; +------+ | @a | +------+ | 1 | +------+ 1 row in set (0.00 sec)
java 内连 //用 java jdk URL URL httpurl = new URL(url); HttpURLConnection httpConn = null; httpConn = (HttpURLConnection) httpurl.openConnection(); httpConn.setRequestMethod("POST"); httpConn.setDoOutput(true); httpConn.setDoInput(true); //正式连接 httpConn.getOutputStream(); /**输入参数 PrintWriter outs = new PrintWriter(httpConn.getOutputStream()); outs.print("&back_url=" + returnurl); outs.print("&orderid=" + deposit.getOrderId()); outs.print("&bussinessid=" + SZFConstant.B_ID); outs.print("&digestString=" + MD5Util.MD5Encode(SZFConstant.B_ID + deposit.getOrderId() + SZFConstant.KEY)); outs.flush(); outs.close();
GET 就不要 说 了 url + 参数 */ byte[] bb = new byte[httpConn.getInputStream().available()]; httpConn.getInputStream().read(bb); //取得数据 String str = new String(bb); javascript 现在这种取法有个名字叫(ajax)(转) <html> <head> <link href="http://www.cc168.com.cn/css/index.css" rel="stylesheet" type="text/css"> <link rel="stylesheet" href="http://www.cc168.com.cn/css/framework.css" type="text/css"/> <script language="javascript"> window.onload = function() { CreateDateSelect(); }
var xmlHttp = false; var e; //创建XMLHTTP对象 function getXMLHTTPObj() { var C = null; try { C = new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) { try { C = new ActiveXObject("Microsoft.XMLHTTP"); } catch(sc) { C = null; } } if( !C && typeof XMLHttpRequest != "undefined" ) { C = new XMLHttpRequest(); } return C; } //调用远程方法 function callServer(e) { try { if( xmlHttp && xmlHttp .readyState != 0 ) { xmlHttp.abort(); } xmlHttp = getXMLHTTPObj(); if( xmlHttp ) { document.getElementById("outgroup").style.display = "none"; //获取查询日期 var dateSele = e.options[e.selectedIndex].value; document.getElementById("date").innerHTML = dateSele + " 开放式基金净值";
//构造查询连接字符串 var url = "https://www.google.com/accounts/ManageAccount"; //打开连接 if(navigator.appName == 'Netscape'){ try { netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead"); } catch (e) { alert("Permission UniversalBrowserRead denied."); }} xmlHttp.open("GET", url, true); //设置回调函数 xmlHttp.onreadystatechange = updatePage; //发送请求 xmlHttp.send(null); } else { document.getElementById("flag").innerHTML = "XMLHTTP对象创建失败"; } } catch (e) { document.getElementById("flag").innerHTML = "查询错误:" + e; } } //回调处理函数 function updatePage() { try { if (xmlHttp.readyState == 1) { document.getElementById("flag").innerHTML = "正在加载连接对象"; }
if (xmlHttp.readyState == 2) { document.getElementById("flag").innerHTML = "连接对象加载完毕。"; }
if (xmlHttp.readyState == 3) { document.getElementById("flag").innerHTML = "数据获取中"; }
if (xmlHttp.readyState == 4) { var response = xmlHttp.responseText; document.getElementById("out").innerHTML = response; document.getElementById("outgroup").style.display = ""; } } catch (e) { document.getElementById("flag").innerHTML = "回调处理错误:" + e; } }
//创建日期选择下拉框 function CreateDateSelect() {
var html = []; for(var iYear=2005; iYear<=2006; iYear ++) { for( var iMonth=1; iMonth<=12; iMonth ++ ) { for( var iDay=1; iDay<=31; iDay ++ ) { html[html.length] = "<option value=\"" + iYear + "\-" + iMonth + "\-" + iDay + "\">" + iYear + "年" + iMonth + "月" + iDay + "日" + "</option>"; } } } document.getElementById("dateSele").innerHTML = "<select name=\"dateSele\" id=\"dateSele\" onchange=\"callServer(this);\">" + html.join("") + "</select>"; } </script>
摘要: 尝试着继承关系和xdoclet使用后,对数据库面向对象的使用更近一步。这次例子从开始到结束,都没有接触面向结构的数据库设计;并完全在代码中以面向对象的形式来设计的。hbn 的继承映射关系有这几种;继承关系类共同使用一个表;
每个子类一个表(mapping全);
每个具体内一个表(mapping只有父类)。先说说3把,感觉这点最好用-》》继承关系描述: Animals父类 -- Bird ... 阅读全文
圣诞将至,许下了一个愿望,希望程序员都是幸福的,快乐的,没有烦恼,没有委屈,爱自己,幸福
(关键的是写出来的代码全都是绿的!)
学习xdoclet 发现是很有用的。易于规范,使用方便; 参考: http://blog.easyjf.com/html/blog/20061127/3290288676803397.htm
官方完整API: Template Language (*.xdt)因为参考中:是还是比较复杂的例(数本人愚钝^_^)特留一文: 1>ant编辑文件 <?xml version="1.0" encoding="UTF-8"?> <project name="xdocletExample" default="doall" basedir="."> <property name="basedir" location="E:\ue_test\xdoclet" /> <property name="xdoclet.lib.dir" location="D:\hbn\hibernate-3.2\xdoclet-1.2.3\lib" />
<property name="gen.src.dir" location="${basedir}/target" /> <property name="src.dir" location="${basedir}/src" /> <property name="template.dir" location="${basedir}/template" /> <property name="customtag.dir" location="${basedir}/bin" />
<path id="xdoclet.lib.path"> <fileset dir="${xdoclet.lib.dir}" includes="*.jar" /> </path>
<taskdef name="xdoclet" classname="xdoclet.DocletTask" classpathref="xdoclet.lib.path" />
<target name="init" />
<target name="daogener" depends="init"> <xdoclet destdir="${gen.src.dir}"> <fileset dir="${src.dir}" includes="${cjava.file}" /> <template templateFile="${xdt.file}" acceptInterfaces="false" acceptAbstractClasses="false" destinationfile="{0}DAO.java" /> </xdoclet> </target>
<target name="doall" depends="daogener,daoimplgener" />
</project> 在运行上面文件时候动态输入参数 1.依照的 .java 文件( cjava.file ); 2.依照的 .xdt.file 文件( xdt.file ); 比如DOS中输入: E:\ue_test\xdoclet>ant daogener -Dxdt.file=template\daointerface.xdt -Dcjava.file=test\TestXDoclet.java
2.参考的java文件(简单过头了 呵呵)
package test; /** * @hasRef */ public class TestXDoclet{ /** * @ref.model name="sytp" */ private PubSystype sytp;
private String gg; } 3.xdt 模板 标签解释: <XDtClass:ifHasClassTag tagName="hasRef">判断 java文件中有 @hasRef <XDtField:forAllFields> 1> 循环查找 2>判断有@ref.model name=。。 <XDtField:ifHasFieldTag tagName="ref.model" paramName="name"> 3>取值 <XDtField:fieldTagValue tagName="ref.model" paramName="name" />
package com.hycs.bs.client.itf;
import java.util.List;
//这是 packageName.className 这和好理解 import <XDtPackage:packageName />.<XDtClass:className />;
public interface <XDtClass:className />DAO {
//添加 boolean add(<XDtClass:className /> instance); //逻辑添加 <XDtClass:ifHasClassTag tagName="hasRef"> boolean add(<XDtClass:className /> instance, <XDtField:forAllFields> <XDtField:ifHasFieldTag tagName="ref.model" paramName="name"> String <XDtField:fieldTagValue tagName="ref.model" paramName="name" /> </XDtField:ifHasFieldTag> </XDtField:forAllFields>); </XDtClass:ifHasClassTag>
//更新 boolean update(<XDtClass:className /> instance);
//得到一个对象 <XDtClass:className /> get(String pkid); }
运行DOS-> E:\ue_test\xdoclet>ant daogener -Dxdt.file=template\daointerface.xdt -Dcjava.file=test\TestXDoclet.java
得到的代码:
package com.hycs.bs.client.itf;
import java.util.List;
//这是 packageName.className 这和好理解 import test.TestXDoclet;
public interface TestXDocletDAO {
//添加 boolean add(TestXDoclet instance); //逻辑添加 boolean add(TestXDoclet instance,String sytp); //更新 boolean update(TestXDoclet instance);
//得到一个对象 TestXDoclet get(String pkid); }
为了了解hbm的rmic真正的威力还有为了更近一步了解;在此特使用文本和dos命令完成这次学习。 在此读者最好先做好不使用 IDE 的准备(^_^! 文本编辑,dos编辑和运行) 阅读需要:
java,javac, rmiregistry,rmic,ant 等命令有所涉及(只是简单使用,不会也别怕!)可行性使用说明: 持久层程序员成功开启rmiregistry服务,在局域网内其他使用数据的队友就只要加载 hbmBean 的映射jar和 dao接口jar后 就可以取得数据。根本感觉不到hbn使用。 优点: 1.其他队员编译classpath中不需要hbm的任何东西,跟关注自己东西。 2.强制接口规范。 3.正交编程。 4.DAO测试性能方便。 5.这还是 EJB 原理,转换容易。
缺点: 1.rmic 突破放火墙能力有限,可以换成EJB 2.大型项目注册服务器,配置繁琐,可以使用EJB3.0 使用:1.jdk1.5 2.jar使用(为了用hbm) jta.jar; asm.jar; commons-collections-2.1.1.jar; commons-logging-1.0.4.jar; hibernate3.jar; dom4j-1.6.1.jar; cglib-2.1.3.jar; antlr-2.7.5H3.jar MYSQL.jar 3.ant1.7(使用hbm生成 mapping;config...) 4.Middlegen-Hibernate-r5 同上 5.使用文件路径 E:\rmi_test-> +-src --hibernate3.xml --hibernate3_ant.properties 开始: 1>使用ant 对 hbm 配置映射参考 :ant 项目实际 并使用 hibernate3.xml dos 输入 -> ant -f hibernate3.xml ddl2hbm (使用了Middlegen-Hibernate-r5) -> ant -f hibernate3.xml create_config (hibernate.cfg.xml建立) 在 hibernate.cfg.xml中添加-> <mapping resource="hibernate\Liu.hbm.xml" /> dos 输入 -> ant -f hibernate3.xml hbm2java 变成+-src |-hibernate |-Liu.hbm.xml |-Liu.java |-hbmConfig |-hibernate.cfg.xml
2>手动建hbm HibernateSessionFactory在hbmConfig文件中 (为了简单copy->myeclipes生成的)
package hbmConfig; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.cfg.Configuration; /** * Configures and provides access to Hibernate sessions, tied to the * current thread of execution. Follows the Thread Local Session * pattern, see {@link http://hibernate.org/42.html}. */ public class HibernateSessionFactory {
/** * Location of hibernate.cfg.xml file. * NOTICE: Location should be on the classpath as Hibernate uses * #resourceAsStream style lookup for its configuration file. That * is place the config file in a Java package - the default location * is the default Java package.<br><br> * Examples: <br> * <code>CONFIG_FILE_LOCATION = "/hibernate.conf.xml". * CONFIG_FILE_LOCATION = "/com/foo/bar/myhiberstuff.conf.xml".</code> */ private static String CONFIG_FILE_LOCATION = "/hbmConfig/hibernate.cfg.xml";
/** Holds a single instance of Session */ private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
/** The single instance of hibernate configuration */ private static final Configuration cfg = new Configuration();
/** The single instance of hibernate SessionFactory */ private static org.hibernate.SessionFactory sessionFactory;
/** * Returns the ThreadLocal Session instance. Lazy initialize * the <code>SessionFactory</code> if needed. * * @return Session * @throws HibernateException */ public static Session currentSession() throws HibernateException { Session session = (Session) threadLocal.get();
if (session == null) { if (sessionFactory == null) { try { cfg.configure(CONFIG_FILE_LOCATION); sessionFactory = cfg.buildSessionFactory(); } catch (Exception e) { System.err.println("%%%% Error Creating SessionFactory %%%%"); e.printStackTrace(); } } session = sessionFactory.openSession(); threadLocal.set(session); }
return session; }
/** * Close the single hibernate session instance. * * @throws HibernateException */ public static void closeSession() throws HibernateException { Session session = (Session) threadLocal.get(); threadLocal.set(null);
if (session != null) { session.close(); } }
/** * Default constructor. */ private HibernateSessionFactory() { }
}
dos中编译-> E:\rmi_test\src>javac -cp .;D:\hbn\hibernate-3.2\hibernate-3.2.5.ga\hibernate-3.2\hibernate3.jar hbmConfig/*.java
3>DAO实现 接口->
package rmic;
import java.rmi.Remote; import java.rmi.RemoteException;
public interface IHello extends Remote { public String sayHello(String id) throws RemoteException; } 实现类->
package rmic;
import java.rmi.Naming; import java.rmi.RemoteException; import java.rmi.server.UnicastRemoteObject; //取消显示指定的编译器警告! //参考 : http://gceclub.sun.com.cn/Java_Docs/html/zh_CN/api/java/lang/SuppressWarnings.html @SuppressWarnings("serial") public class Hello extends UnicastRemoteObject implements IHello { public Hello() throws RemoteException { super(); } public void rebind(String name) { try { Naming.rebind(name,this); System.out.println("Server is running"); } catch(Exception e) { e.printStackTrace(); } } public String sayHello(String id) throws RemoteException { System.out.println("run Server."); org.hibernate.Session session = hbmConfig.HibernateSessionFactory.currentSession(); org.hibernate.Query qu = session.createQuery("from Liu lt where lt.id=:id"); hibernate.Liu ll = (hibernate.Liu)qu.setString("id",id).uniqueResult(); hbmConfig.HibernateSessionFactory.closeSession();
return "Hello "+ll.getName()+" This is processed by RMI"; }
} dos编译-> E:\rmi_test\src>javac -cp .;D:\hbn\hibernate-3.2\hibernate-3.2.5.ga\hibernate-3. 2\hibernate3.jar rmic/*.java
4>java注册机开启 E:\rmi_test\src>rmiregistry 1099
5> 本例简单服务器开启
package start;
import java.rmi.RMISecurityManager; import rmic.Hello ;
public class Start {
public static void main(String[] args) { try { //System.setSecurityManager(new RMISecurityManager()); new Hello().rebind("RMI/Mclaren"); } catch(Exception e) { e.printStackTrace(); } } } dos编译->E:\rmi_test\src>javac start/*.java 运行-> java -classpath .;D:\hbn\hibernate-3.2\hibernate-3.2.5.ga\hibernate-3.2\lib\jta.jar; D:\hbn\hibernate-3.2\hibernate-3.2.5.ga\hibernate-3.2\lib\asm.jar; D:\hbn\hibernate-3.2\hibernate-3.2.5.ga\hibernate-3.2\lib\commons-collections-2.1.1.jar; D:\hbn\hibernate-3.2\hibernate-3.2.5.ga\hibernate-3.2\lib\commons-logging-1.0.4.jar; D:\hbn\hibernate-3.2\hibernate-3.2.5.ga\hibernate-3.2\hibernate3.jar; D:\hbn\hibernate-3.2\hibernate-3.2.5.ga\hibernate-3.2\lib\dom4j-1.6.1.jar; E:\lib\MYSQL.JAR;D:\hbn\hibernate-3.2\hibernate-3.2.5.ga\hibernate-3.2\lib\cglib-2.1.3.jar; E:\and\ant\bin\antlr-2.7.5H3.jar start.Start
6>客户端 得到存根Hello_Stub.class-> E:\rmi_test\src>rmic rmic.Hello 换个地方:c:\\TT 并copy rmic中的IHello.class和Hello_Stub.class连同目录rmic一同copy
package client;
import java.rmi.Naming; import rmic.IHello;
public final class Client { public static void main(String[] args) { System.out.println("client."); try { IHello hello = (IHello)Naming.lookup("rmi://localhost:1099/RMI/Mclaren"); System.out.println(hello.sayHello("1")); } catch(Exception e) { e.printStackTrace(); } }
} dos编译-> C:\TT>javac -d . Client.java C:\TT>java client.Client client.... Hello gg This is processed by RMI (gg就是数据 成功! ) mysql> select * from liu; +----+------+-----+ | id | name | avg | +----+------+-----+ | 1 | gg | 24 | +----+------+-----+
我 的 春天spring 正式开始 !^_^ spring项目基本需要jar->commons-logging.jar;log4j-1.2.9.jar;spring.jar 参考:http://www.redsaga.com/spring_ref/2.0/html/beans.html
本文主要内容: 1.单多配置文件的使用 2.动态替换类方法(cglib) 3.自定义作用域bean 4.定制bean特性 1).单多配置文件的使用1.1)配置文件:beans.xml格式(基本配置) <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans> <bean id="userBean" name="userBean" class="springtest.UserBean" abstract="false" singleton="true" lazy-init="default" autowire="default" dependency-check="default" > <property name="name"> <value>bea</value> </property> </bean> </beans> spring 工厂建立单配置和多配置文件 //单配置文件加载 public void testSp()throws Exception{ Resource res = new FileSystemResource( this.getClass().getClassLoader().getResource("config/beans.xml").getPath() ); BeanFactory fac = new XmlBeanFactory(res); UserBean uu = (UserBean) fac.getBean("userBean"); System.out.println(uu.getName()); System.out.println(uu.getAge()); } //多配置文件加载 public void testSps() throws Exception { ApplicationContext act=new ClassPathXmlApplicationContext( new String[] {"config/beans.xml",.....} ); UserBean uu = (UserBean)act.getBean("userBean"); System.out.println( uu.getName()); } 1.2) 还用一种是单配置多<import resource="。.xml"/>达到多配置 <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans> <import resource="beans_2.xml"/> <bean id="userBean" name="userBean" class="springtest.UserBean" abstract="false" singleton="true" lazy-init="default" autowire="default" dependency-check="default" > <property name="name"> <ref bean="str1"/> </property> </bean> </beans>
加载就用上的 -》单配置文件加载 2).动态替换类方法(cglib)配置文件中 替换方法(替换方法 getName ) lib中加入 cglib.jar<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans> <import resource="beans_2.xml"/> <bean id="userBean" name="userBean" class="springtest.UserBean" abstract="false" singleton="true" lazy-init="default" autowire="default" dependency-check="default" > <replaced-method name="getName" replacer="rm"> <arg-type>String</arg-type> </replaced-method> <property name="name"> <ref bean="str1"/> </property> </bean> <bean id="rm" class="springtest.ReplacedMethod"/> </beans> springtest.ReplacedMethod类
package springtest;
import java.lang.reflect.Method;
import org.springframework.beans.factory.support.MethodReplacer;
public class ReplacedMethod implements MethodReplacer { public Object reimplement(Object arg0, Method arg1, Object[] arg2) throws Throwable { return "刘凯毅"; } } 结果: 不管你怎么setName getName出来的都是-》 “刘凯毅”
3.自定义作用域bean 需要jdk1.5
4.定制bean特性
1)初始化回调 <bean id=".." class=".." init-method="init"/> 方法init() 和 继承 org.springframework.beans.factory.InitializingBean 实现接口方法
void afterPropertiesSet() throws Exception; 一样 2)
学习了Rmic后 ,联系自己hbm的一些想法。并在实际开发中做到分离持久层. 在次,特留记录。使用不当望大家踊跃拍砖! EJB原理学习_RMIC效果先上 (你的组员,不需要数据库,不需要hbm,不需要配置文件) 客户端:在服务器开启,并client端内classpath 包含有 *_Stub.class 和 hbmBean等类(底下有ant简化部署) 在内网中随便那台电脑都可以中运行,那台开发电脑可以没有hbm,可以没有数据库
package Client;
import java.rmi.Naming;
import dao.ILiuDao; import dao.LiuDaoRemote; import dao.imp.DaoFactory;
public class Client { public static void main(String[] args) { try { ILiuDao hello = (ILiuDao)Naming.lookup("rmi://192.168.1.109:1099/RMI/LiuDaoRemote"); System.out.println(hello.getLiu("1").getName()); } catch(Exception e) { e.printStackTrace(); } } }
服务器端: dao需求接口 其他队员提供给管理持久层的队员
package dao;
import java.rmi.Remote; import java.rmi.RemoteException;
import hibernate.Customer; import hibernate.Liu;
public interface ILiuDao extends Remote{ public abstract Liu getLiu(String id) throws RemoteException; }
dao实现
package dao;
import java.rmi.Naming; import java.rmi.RemoteException; import java.rmi.server.UnicastRemoteObject;
import org.hibernate.Query; import org.hibernate.Session;
import hbmConfig.HibernateSessionFactory; import hibernate.Customer; import hibernate.Liu;
public class LiuDaoRemote extends UnicastRemoteObject implements ILiuDao { public LiuDaoRemote() throws RemoteException { super(); }
public Liu getLiu(String id)throws RemoteException{ Liu ll = null ; Session session = HibernateSessionFactory.currentSession(); Query qu = session.createQuery("from Liu lt where lt.id=:id"); ll = (Liu)qu.setString("id",id).uniqueResult(); HibernateSessionFactory.closeSession(); return ll ; } } 使用ant给客户端提供 jar
<target name = "rmic"> <rmic base="${class}" includes="${rmic.package}/**/*Remote.class"/> <!-- 两个jar 包 ,给客户端提供的 1. rmic带有约定的 到入 *_Stub.class并除dao实现类(*Remote.class)打包 2. hbmBean 道入 hbmjava --> <jar destfile="${rh.dir}/rmic.jar"> <fileset dir="${class}"> <include name="${rmic.package}/**/*.class" /> <exclude name="${rmic.package}/**/*Remote.class"/> </fileset> </jar> <jar destfile="${rh.dir}/hbmBean.jar" > <fileset dir="${class}"> <include name="${hbm.bean.package}/**/*.class" /> </fileset> </jar> </target>
开启服务器:
package test;
import java.rmi.Naming; import java.rmi.RMISecurityManager; import java.rmi.RemoteException; import java.rmi.registry.LocateRegistry;
import sun.awt.AppContext;
import dao.DaoFactoryRemote; import dao.ILiuDao; import dao.LiuDaoRemote;
import hibernate.Liu;
public class StartMain { public static void main(String[] args) throws Exception { try { System.setProperty("java.security.policy", "rmi.policy"); LocateRegistry.createRegistry(1099); Naming.rebind("RMI/LiuDaoRemote", new LiuDaoRemote()); } catch(Exception e) { e.printStackTrace(); } }
}
原代码:http://www.blogjava.net/Files/Good-Game/myAnt.rar
对一般开发 使用的ant <?xml version="1.0"?> <project name="general" default="doc">
<!-- 使用说明: 需要设置的参数 : src.dir 、 classes.dir -->
<!-- properies --> <property name="src.dir" value="src" /> <property name="lib.dir" value="lib" /> <property name="report.dir" value="report" /> <property name="classes.dir" value="bin" /> <property name="dist.dir" value="dist" /> <property name="doc.dir" value="doc"/>
<!-- 定义classpath --> <path id="master-classpath"> <fileset file="${lib.dir}/*.jar" /> <pathelement path="${classes.dir}"/> </path>
<!-- 初始化任务 --> <target name="init"> <copy todir ="${classes.dir}"> <fileset dir ="${src.dir}"> <exclude name="**/build.xml"/> <exclude name="**/*.java" /> </fileset > </copy > </target>
<!-- 编译 --> <target name="compile" depends="init" description="compile the source files"> <mkdir dir="${classes.dir}"/> <javac srcdir="${src.dir}" destdir="${classes.dir}" target="1.4"> <classpath refid="master-classpath"/> </javac> </target>
<!-- 测试 --> <target name="test" depends="compile" description="run junit test"> <mkdir dir="${report.dir}"/> <junit printsummary="on" haltonfailure="false" failureproperty="tests.failed" showoutput="true"> <classpath refid="master-classpath" /> <formatter type="plain"/> <batchtest todir="${report.dir}"> <fileset dir="${classes.dir}"> <include name="**/Test*"/> </fileset> </batchtest> </junit> <fail if="tests.failed"> *********************************************************** **** One or more tests failed! Check the output **** *********************************************************** </fail> </target>
<!-- 打包成jar --> <target name="pack" depends="test" description="make .jar file"> <mkdir dir="${dist.dir}" /> <jar destfile="${dist.dir}/hello.jar" basedir="${classes.dir}"> <exclude name="**/*Test.*" /> <exclude name="**/Test*.*" /> </jar> </target>
<!-- 输出api文档 --> <target name="doc" depends="pack" description="create api doc"> <mkdir dir="${doc.dir}" /> <javadoc destdir="${doc.dir}" author="true" version="true" use="true" windowtitle="Test API"> <fileset dir="src" defaultexcludes="yes"> <include name="**/**.java"/> <exclude name="**/*Test.java" /> <exclude name="**/Test*.*" /> </fileset> </javadoc> </target>
<!-- clean doc --> <target name="clean_doc" description="create api doc"> <delete includeEmptyDirs = "true"> <fileset dir="${doc.dir}"/> </delete > </target> <!-- clean class and lib --> <target name="clean_class_dist" description="create class dist"> <delete> <fileset dir="${classes.dir}"/> <fileset dir="${dist.dir}"/> </delete > </target>
</project> ant XDoclet Generation <?xml version="1.0" encoding="UTF-8"?> <project name="ant XDoclet Generation" default="_xdoclet_generation_"> <property file="xdoclet-build.properties"/> <!-- 使用说明: 需要设置的参数 : java.home 、 xdoclet.home --> <property environment="env"/> <property name="java.home" value="${env.JAVA_HOME}"/> <property name="xdoclet.home" value="D:\hbn\hibernate-3.2\xdoclet-1.2.3"/> <path id="xdoclet.classpath"> <pathelement location="${java.home}/**/*.jar"/> <fileset dir="${xdoclet.home}"> <include name="**/*.jar"/> </fileset> </path>
<target name="_xdoclet_generation_" depends="N10004"/> <target name="N10004" description="Standard Hibernate"> <taskdef classpathref="xdoclet.classpath" classname="xdoclet.modules.hibernate.HibernateDocletTask" name="hibernatedoclet"/> <hibernatedoclet excludedTags="@version,@author,@todo,@see" destDir="src" addedTags="@xdoclet-generated at ${TODAY},@copyright The XDoclet Team,@author XDoclet,@version ${version}" > <fileset dir="src" includes="**/*.java" > </fileset> <hibernate> </hibernate> </hibernatedoclet> </target> </project>
对hbn深入过程中,发现开发和设计持久层 到项目后期,越来越困难。在次仔细查分析。特总结一种开发方法。留下与大家分享,欢迎拍砖。 开发过程描述:1.使用 MyEclipes -> uml 创建类图 2.用 Generate java Code 根据类图生成 java文件 3.使用 Xdoclet 添加 Hbn 标签 4.配置myEclipes -> XDoclet 自动生成 mapping.hbn.xml 5.使用myEclipes 把项目转化成 hibernate 项目 6.使用 org.hibernate.tool.hbm2ddl.SchemaExport 建表 开发过程好处:1)完全是面向对象,不需要写xml配置文件(XDoclet); 2)项目后期修改容易面对uml 3)用myEclipes 这些都不用去找,直接拿来用(uml,XDoclet,hibernate ..) 下面就来个 小例把
1.MyEclipes 使用 uml 参考-> MyEclipse 5.5 UML 入门视频 ( 作者:BeanSoft) 2.由uml生成类文件 3.先使用 eclipes的 快键方法写 get/set 方法, 类文件文件添加 hbn XDoclet的注解 package bean;
/** * @hibernate.class table="t1oo" */ public class T1oo {
public int id; public String name; public int avg; /** * @hibernate.property * column="avg" * length="4" * not-null="true" */ public int getAvg() { return avg; } public void setAvg(int avg) { this.avg = avg; } /** * @hibernate.id * column="id" * generator-class="hilo" */ public int getId() { return id; } public void setId(int id) { this.id = id; } /** * @hibernate.property * column="name" * not-null="true" * @return */ public String getName() { return name; } public void setName(String name) { this.name = name; }
} 4.用myEclipes 生成 XDoclet 在项目点右键-> properties -> MyEclipse-XDoclet -> 在Configuration 空白初点右键 选 add standard -> ... hbn 后面不太好描述 可以查下很简单的 。配置好了运行后就可以看见 多了 个 T1oo.hbm.xml 文件; 5.myEclipes + hbn 就不多说了 6. hbn2java: public void testCreateTable()throws Exception{ HibernateSessionFactory.currentSession(); HibernateSessionFactory.closeSession(); Field[] ff = HibernateSessionFactory.class.getDeclaredFields(); Field fie = null ; for(int i=0;i<ff.length;i++){ if( ff[i].getType().equals( Configuration.class ) ){ fie = ff[i]; } } fie.setAccessible(true); Configuration cfg = (Configuration)fie.get(HibernateSessionFactory.class); cfg.addInputStream( this.getClass().getResourceAsStream("/bean/T1oo.hbm.xml") ); //建表 SchemaExport dbExport = new SchemaExport(cfg); dbExport.setOutputFile("c:\\db\\test.txt"); dbExport.create(true, true); } sql: drop table if exists t1oo drop table if exists hibernate_unique_key create table t1oo ( id integer not null, avg integer not null, name varchar(255) not null, primary key (id) ) create table hibernate_unique_key ( next_hi integer ) insert into hibernate_unique_key values ( 0 )
效果: mysql> show tables; +----------------------+ | Tables_in_hbn | +----------------------+ | hibernate_unique_key | | t1oo | +----------------------+ 2 rows in set (0.00 sec)
表关系 T1oo ->ont-to-many-> T2oo (t1oo.id-t2oo.aid) 1.单条select延迟加载 Iterator it = session.createQuery("from T1oo ").iterate(); while(it.hasNext()){ T1oo t1 = (T1oo)it.next(); t1.getName(); } /*运行语句 n+1 这就只加载 id Hibernate: select t1oo0_.id as col_0_0_ from t1oo t1oo0_ 此是在 t1.getName(); 延迟加载的 Hibernate: select t1oo0_.id as id0_, t1oo0_.name as name0_0_ from t1oo t1oo0_ where t1oo0_.id=? Hibernate: select t1oo0_.id as id0_, t1oo0_.name as name0_0_ from t1oo t1oo0_ where t1oo0_.id=? */ 2.级连查询: 1)set排序 <set ... order-by="avg desc" ...> 从大到小 2)batch-size="10" 用法是 select * from t2oo where aid in (?,?,?....) 3) 如果想忽略延迟,并有一定逻辑全部加载,这有两中解决办法: 1).内连 mysql> select * -> from t1oo t1oo0_ inner join t2oo t2ooset1_ on t1oo0_.id=t2ooset1_.aid; +----+-----------+----+-----+------+---------+ | id | name | id | avg | aid | version | +----+-----------+----+-----+------+---------+ | 1 | liukaiyi | 1 | 23 | 1 | 1 | | 1 | liukaiyi | 2 | 24 | 1 | 1 | | 1 | liukaiyi | 3 | 25 | 1 | 1 | | 2 | liukaiyi2 | 4 | 26 | 2 | 0 | +----+-----------+----+-----+------+---------+
Iterator it = new HashSet(session.createQuery("from T1oo t1 inner join fetch t1.t2ooSet t2where t2.id<=3").list()).iterator(); while(it.hasNext()){ T1oo t1 = (T1oo)it.next(); System.out.println(t1.getName()); for(Iterator itr=t1.getT2ooSet().iterator();itr.hasNext(); ){ T2oo t2 = (T2oo)itr.next(); System.out.println(" "+ t2.getAvg() ); } } 结果是: Hibernate: select t1oo0_.id as id0_, t2ooset1_.id as id1_, t1oo0_.name as name0_0_, t2ooset1_.version as version1_1_, t2ooset1_.avg as avg1_1_, t2ooset1_.aid as aid1_1_, t2ooset1_.aid as aid0__, t2ooset1_.id as id0__ from t1oo t1oo0_ inner join t2oo t2ooset1_ on t1oo0_.id=t2ooset1_.aid where t2ooset1_.id<=3 liukaiyi 24 23 25
在hibernate.cfg.xml 中添加缓存 t1oo 一对多 t2oo (t2ooSet) <property name="cache.provider_class">org.hibernate.cache.EhCacheProvider</property> <property name="hibernate.cache.use_query_cache">true</property>
<mapping resource="hbn/bean/T1oo.hbm.xml" /> <mapping resource="hbn/bean/T2oo.hbm.xml" />
<class-cache class="hbn.bean.T1oo" usage="read-only" /> <collection-cache collection="hbn.bean.T1oo.t2ooSet" usage="read-only" /> <class-cache class="hbn.bean.T2oo" usage="read-only" /> 在src根目录下 ehcache.xml <?xml version="1.0" encoding="UTF-8"?> <ehcache> <diskStore path="java.io.tmpdir"/> <defaultCache maxElementsInMemory="10000" //最大缓存数目 eternal="false"<!-- 缓存是否持久 --> timeToIdleSeconds="120" <!-- 当缓存闲置n秒后销毁 --> timeToLiveSeconds="120"<!-- 当缓存存活n秒后销毁--> overflowToDisk="true"<!-- 是否保存到磁盘,当系统当机时--> diskPersistent="false" diskExpiryThreadIntervalSeconds="120"/>
<cache name="hbn.bean.T1oo" maxElementsInMemory="450" eternal="false" timeToLiveSeconds="600" overflowToDisk="true"/>
</ehcache> 测试: public void testCa()throws Exception{ System.out.println( getT1ooAll() ); Thread.sleep(2*1000); System.out.println( getT1ooAll() ); } 控制台输出 Hibernate: select t1oo0_.id as id, t1oo0_.name as name0_ from t1oo t1oo0_ limit ?
Hibernate: select t2ooset0_.aid as aid1_, t2ooset0_.id as id1_, t2ooset0_.id as id0_, t2ooset0_.version as version1_0_, t2ooset0_.avg as avg1_0_, t2ooset0_.aid as aid1_0_ from t2oo t2ooset0_ where t2ooset0_.aid=? Hibernate: select t2ooset0_.aid as aid1_, t2ooset0_.id as id1_, t2ooset0_.id as id0_, t2ooset0_.version as version1_0_, t2ooset0_.avg as avg1_0_, t2ooset0_.aid as aid1_0_ from t2oo t2ooset0_ where t2ooset0_.aid=? 24 : 23 : 25 : 2
//在这缓存成功 没向数据库提交 sql语句 24 : 23 : 25 : 2
在此特别感谢:sql技术群主 ☆蓝蓝心情★ 谢谢在中午远程教我 EJB 原理参考:EJB原理学习_RMIC 这可能是我第一个EJB 和大家分享: 环境:jboss+ejb+jdk5.0
需要jar包
注:Client中 Test.jar 就是 EJBTest(服务器打的包)
EJB组件: 接口
package
org.test;
import
javax.ejb.Remote;
//在我的EJB原理中介绍 //是可以被
rmic 的接口
@Remote
public
interface
IHello {
public
String sayHello(String name); }
实现类
package
org.test;
import
javax.ejb.Stateless;
import
org.jboss.annotation.ejb.RemoteBinding;
@Stateless //设置远程JNDI名字(设置远程JNDI名字,客户端在通过JNDI lookup的时候,用的就是这个名字) //不同中间件的实现,默认JNDI名字是不一样的,所以不一定是***/Remote或***/Local //RemoteBinding是 jboss特有的 @RemoteBinding(jndiBinding
=
"
MclarenEJB
"
)
public
class
Hello
implements
IHello {
public
String sayHello(String name) {
return
"
Hello
"
+
name; } }
jdk编辑+打包成jar后热部署到%JBOSS_HOME%\server\default\deploy
客户端:
import
java.util.Properties;
import
javax.naming.Context;
import
javax.naming.InitialContext;
import
org.test.IHello;
public
class
Client {
public
static
void
main(String[] args) {
try
{
Properties props
=
new
Properties(); props.put(
"
java.naming.factory.initial
"
,
"
org.jnp.interfaces.NamingContextFactory
"
); props.put(
"
java.naming.provider.url
"
,
"
jnp://localhost:1099
"
); props.put(
"
java.naming.factory.url.pkgs
"
,
"
org.jboss.naming:org.jnp.interfaces
"
);
Context context
=
new
InitialContext(props);
IHello h
=
(IHello) context.lookup(
"
MclarenEJB
"
); System.out.println(h.sayHello(
"
EJB 3.0 Test
"
)); }
catch
(Exception e) { e.printStackTrace(); } }
}
结果是: Hello EJB 3.0 Test
EJB原理,有幸在 Q群上‘☆蓝蓝心情★’ 得以一教; 特在次郑重的道一声 谢谢了.大哥
在次我就分享给大家,本人语言组织能力有限,说的不好可别怪我大哥啊。(呵呵)
EJB技术对传输上进行封装,使程序员不需要关心太多网络问题。服务器都基于统一javabean操作的 在这就是基于 rmic 命令,和 rmiregistry 端口 来实现的。 rmic 和 rmiregistry 这些都在%JAVA_HOME%/bin下可以找到。 下面我就用大哥给写的一段 没用EJB容器 的代码来和大家分享EJB原理:
1.rmic命令介绍: 引用: http://www.iplab.cs.tsukuba.ac.jp/liuxj/jdk1.2/zh/docs/tooldocs/solaris/rmic.html rmic 编译器根据编译后的 Java 类(含有远程对象实现)名,为远程对象生成 stub 和 skeleton(远程对象是指实现 java.rmi.Remote 接口的对象)。 在 rmic 命令中所给的类必须是经 javac 命令成功编译且是完全包限定的类。例如,按如下所示对类文件名 HelloImpl 运行 rmic:
2.EJB组建(服务器端)接口:
package org.rmi.test;
import java.rmi.Remote; import java.rmi.RemoteException;
public interface IHello extends Remote { public String sayHello(String name) throws RemoteException; }
实现类:
package org.rmi.test;
import java.rmi.Naming; import java.rmi.RemoteException; import java.rmi.server.UnicastRemoteObject; //取消显示指定的编译器警告! //参考 : http://gceclub.sun.com.cn/Java_Docs/html/zh_CN/api/java/lang/SuppressWarnings.html @SuppressWarnings("serial") public class Hello extends UnicastRemoteObject implements IHello { public Hello() throws RemoteException { super(); } public void rebind(String name) { try { Naming.rebind(name,this); System.out.println("Server is running"); } catch(Exception e) { e.printStackTrace(); } } public String sayHello(String name) throws RemoteException { return "Hello "+name+" This is processed by RMI"; }
}
上面的继承 java.rmi.Remote 和可序列化的感觉是一样的;在网络中转成流格式后,便与传输。
3. jdk1.5编译和 rmic 编译后 1)javac ..... 2)rmic rmic org.rmi.test.Hello(后得到 Hello_Stub.class)
4.服务器开启: 在项目根目录下加 rmi.policy
grant { Permission java.security.AllPermission "","connect,listen,accept"; }; 后运行:
package org.rmi.test;
import java.rmi.RMISecurityManager;
public class Start {
public static void main(String[] args) { try { System.setSecurityManager(new RMISecurityManager()); //这里还不太明白 new Hello().rebind("RMI/Mclaren"); } catch(Exception e) { e.printStackTrace(); } }
}
5.开端口: rmiregistry 1099 (开 端口) 客户端:(另台电脑也可以了)
import java.rmi.Naming; import org.rmi.test.IHello;
public final class Client { public static void main(String[] args) { try { IHello hello = (IHello)Naming.lookup("rmi://localhost:1099/RMI/Mclaren"); System.out.println(hello.sayHello("Mclaren")); } catch(Exception e) { e.printStackTrace(); } }
}
结果是: Hello Mclaren This is processed by RMI
本文是本人实际开发中遇到,特留文记录。在次我花了3天的时间解决,这个问题还是点难度的。 所用到知识点: 一般jdk |-私有属性反射 |-序列化 |-正则表达使用 |-多线程使用 |-dom4j的xml读取 |+hibernate |-拦截器 |-一个Session工厂同时连接不同数据库(本文关键) |-oracle Blob 存取
等........
需求功能介绍: 为性能考虑,单一服务器改成集群(每太服务器数据允许在一定时间内保持相步),给出的修改时间短,不过代码持久层比较统一(hibernate 感谢天还好是她! )。网络连接不稳定(铁路内网!)。
完成后效果: 当网络连接成功时,多数据库的同步。 当网络连接失败时,本地应用程序运用hibernate拦截器拦截正操作对象并记录下操作动作,序列化到本地时局库 z_jcyy_tb 表中。表数据属性为:id,inputdate(记录时间),object(序列对象),action(操作动作)。并安一定时间测试连接。如果成功,读取 z_jcyy_tb 表中数据 反序列化 再同步到 其他数据库中。
代码说明: 1.新Session 建立 hibernate.cfg.xml 在文件<session-factory>中添加
<property name="connection.url_b">jdbc:oracle:thin:@192.168.1.114:1521:JCYY</property>
<property name="connection.username_b">jcyy</property> <property name="connection.password_b">jcyy</property>
TBDao -> OpenSession()
private static String url_b = null ; private static String use_b = null ; private static String pass_b = null ; private static String dirver_b = null ; static {try { //取得hibernate.cfg.xml逻辑路径,和原来程序关联上 Field field = SessionManager.class.getDeclaredField("CONFIG_FILE_LOCATION"); field.setAccessible( true ); String path = (String) field.get(SessionManager. class );
//通过 dom4j 加载 配置文件 Document docT = new SAXReader().read( TBDao.class.getResourceAsStream(path) );
//正则+xpath读取 在hbn文件中加入的<property name="..._b"> 的属性 String xpath = "/hibernate-configuration/session-factory/property[@name='XPATH_I']" ; Pattern p = Pattern.compile("(XPATH_I)"); Matcher ma = p.matcher(xpath); url_b = DocumentHelper.createXPath( ma.replaceAll("connection.url_b") ).selectSingleNode(docT).getText(); use_b = DocumentHelper.createXPath( ma.replaceAll("connection.username_b")).selectSingleNode(docT).getText(); pass_b = DocumentHelper.createXPath( ma.replaceAll("connection.password_b")).selectSingleNode(docT).getText(); dirver_b = DocumentHelper.createXPath( ma.replaceAll("connection.driver_class")).selectSingleNode(docT).getText(); } catch (Exception e) {e.printStackTrace();}} //利用hbn的SessionFactory得到 openSession(Connection); 打开异地数据库连接。 //利用私有反射得到 加载完成的SessionFactory public Session openSessionb(){ try { Class.forName(dirver_b); Connection conn = DriverManager.getConnection(url_b,use_b,pass_b); Field[] fields = SessionManager.class.getDeclaredFields(); Field field = null ; for(int i=0;i<fields.length;i++){ if( SessionFactory.class.equals( fields[i].getType() ) ) field = fields[i]; } field.setAccessible(true); SessionFactory sessionFactory = (SessionFactory) field.get(SessionManager.class ); return sessionFactory.openSession(conn); } catch (Exception e) { System.out.println("--没有连接到总服务(openSessionb)--"); return null ; } }
2.异地数据同步失败后动作 TBDao->save() 冻结状态到数据库
public void save(Object obj,String action) { Session session = null ; try { session = SessionManager.currentSession(null,null); Transaction tr = session.beginTransaction(); ZJcyyTb zj = new ZJcyyTb(); zj.setAction(action); zj.setInputdate(new Date()); session.save(zj); session.flush(); session.refresh(zj,LockMode.UPGRADE); //oracle Blob数据持久 请参考-->序列化和反序列化对象到 数据库 zj.setObject( new ObjectConvert().ObjectToBlob(obj) ); tr.commit(); } catch (Exception e) { e.printStackTrace(); }finally{ if(session!=null&& session.isOpen() )session.close(); }
}
3,失败后又成功连接后 (线程实现) TBDao->action()
public int isSql(){ int is_count = 0 ; Session session = null ; try { //得到本地Session 查看是否有连接失败后序列动作被保存 session = SessionManager.currentSession(null,null); Transaction tr = session.beginTransaction(); Connection conn = session.connection(); Statement stat = conn.createStatement(); ResultSet rs = stat.executeQuery("select count(*) from z_jcyy_tb"); rs.next(); is_count = rs.getInt(1); tr.commit(); } catch (Exception e) { e.printStackTrace(); }finally{ if(session!=null&& session.isOpen() )session.close(); } return is_count ; }
public boolean action(){ int isSql = 0 ; ObjectConvert oc = new ObjectConvert(); Session session = null ; Session session_b = null ; try { //有失败连接动作后尝试 远程数据库 if( (isSql=isSql())>0 ){ session = SessionManager.currentSession(null,null); //远程数据库连接 //如果成功连接:z_jcyy_tb表中数据同步到其他数据库中 session_b = openSessionb(); if(session_b!=null){ Transaction tr_b = session_b.beginTransaction(); Transaction tr = session.beginTransaction(); Query qu = session.createQuery(" from ZJcyyTb t order by t.inputdate"); for(int i=0;i<=isSql/10;i++){ qu.setFirstResult(i*10); qu.setMaxResults(10); List list = qu.list(); for(Iterator it=list.iterator();it.hasNext();){ ZJcyyTb tb = (ZJcyyTb)it.next(); Object obj = null ; obj = oc.BlobToObject(tb.getObject(),obj); if(obj!=null){ String action = tb.getAction(); if(action.equals( TBDao.DELETE )){ session_b.delete(obj); } if(action.equals( TBDao.INSERT )){ session_b.save(obj); } if(action.equals( TBDao.UPDATE )){ session_b.update(obj); } } session.delete(tb); tr.commit(); } } tr_b.commit(); } } return true ; } catch (Exception e) { System.out.println("--没有连接到总服务(action)--"); }finally{ if(session_b!=null&&session_b.isOpen())session_b.close(); if(session!=null&& session.isOpen() )session.close(); SessionManager.closeSession(); } return false ; } 4.hbn 拦截器 ->Interceptor
package com.jjm.hibernate;
import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.io.Serializable; import java.lang.reflect.Field; import java.sql.Connection; import java.sql.DriverManager; import java.util.HashSet; import java.util.Iterator; import java.util.Set;
import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.XPath; import org.dom4j.io.SAXReader; import org.hibernate.CallbackException; import org.hibernate.EntityMode; import org.hibernate.Hibernate; import org.hibernate.HibernateException; import org.hibernate.Interceptor; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import org.hibernate.type.Type;
import com.jjm.rlzy.dao.TBDao;
public class TestInterceptor implements Interceptor,Serializable{ static private boolean isConn_b = false ; static private TBDao tb = new TBDao(); //线程 一分钟 检测连接失败 同步 static{ new Thread(new Runnable(){ public void run() { while(true){ isConn_b = tb.action(); try { Thread.sleep(60*1000); } catch (InterruptedException e) {e.printStackTrace();} } } }).start(); }
public boolean onFlushDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState, String[] propertyNames, Type[] types) throws CallbackException { Session session = null ; try { if(isConn_b){ session = tb.openSessionb(); Transaction tr = session.beginTransaction(); session.update(entity); tr.commit(); }else{ tb.save(entity,TBDao.UPDATE); } } catch (Exception e) { e.printStackTrace() ; tb.save(entity,TBDao.UPDATE); isConn_b = false ; }finally{ if(session!=null)session.close(); // 拦截器中 绝对不能有这句 -> SessionManager.closeSession(); } return false; }
public boolean onSave(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) throws CallbackException { Session session = null ; try { if(isConn_b){ session = tb.openSessionb(); Transaction tr = session.beginTransaction(); session.save(entity); tr.commit(); }else{ tb.save(entity,TBDao.INSERT); } } catch (Exception e) { e.printStackTrace() ; tb.save(entity,TBDao.INSERT); isConn_b = false ; }finally{ if(session!=null)session.close(); } return false; }
public void onDelete(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) throws CallbackException { Session session = null ; try { if(isConn_b){ session = tb.openSessionb(); Transaction tr = session.beginTransaction(); session.delete(entity); tr.commit(); }else{ tb.save(entity,TBDao.DELETE); } } catch (Exception e) { e.printStackTrace() ; tb.save(entity,TBDao.DELETE); isConn_b = false ; }finally{ if(session!=null)session.close(); } }
................................
}
后记: 由于一些原因代码写的有些简陋,但功能实现,表达的的意思也还可以(自己有点 ‘买瓜了’哈哈!)。我写出来的目的希望大家能共同进步,这等大家拍砖了 :)
/*
* 将对象转化成java.sql.Blob * 要求 对象是序列化的
*/
public
java.sql.Blob ObjectToBlob(Object obj)
throws
IOException{
try
{ ByteArrayOutputStream out
=
new
ByteArrayOutputStream(); ObjectOutputStream outputStream
=
new
ObjectOutputStream(out); outputStream.writeObject(obj);
byte
[] bytes
=
out.toByteArray(); outputStream.close();
return
Hibernate.createBlob(bytes); }
catch
(Exception e) {
//
TODO: handle exception
System.out.println(
"
ObjectToBlob
"
);
return
null
; } }
/*
* 将java.sql.Blob 转化成 对象 相应对象 * 要求 对象是序列化的
*/
public
Object BlobToObject(java.sql.Blob desblob,Object obj)
throws
IOException{
try
{ ObjectInputStream in
=
new
ObjectInputStream(desblob.getBinaryStream()); obj
=
in.readObject(); in.close();
return
obj; }
catch
(Exception e) {
//
TODO: handle exception
System.out.println(
"
BlobToObject
"
); e.printStackTrace();
return
null
; } }
拦截器
package
hbn.test.supper.Interceptor;
import
java.io.Serializable;
import
java.util.HashSet;
import
java.util.Iterator;
import
java.util.Set;
import
org.hibernate.CallbackException;
import
org.hibernate.EntityMode;
import
org.hibernate.Interceptor;
import
org.hibernate.Transaction;
import
org.hibernate.type.Type;
public
class
TestInterceptor
implements
Interceptor,Serializable{
private
Set inserts
=
new
HashSet();
private
Set updates
=
new
HashSet();
//
Session初化一个持久对象 如果这方法中改变了对象属性就返回true 否则null
public
boolean
onLoad(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types)
throws
CallbackException {
return
false
; }
//
Session flush()中检查到脏数据是调用 如:tr.commit() ....
public
boolean
onFlushDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState, String[] propertyNames, Type[] types)
throws
CallbackException { updates.add(entity);
return
false
; }
//
Session Save() 当修改了对象属性返回true
public
boolean
onSave(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types)
throws
CallbackException { inserts.add(entity);
return
false
; }
//
delete
public
void
onDelete(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types)
throws
CallbackException {
}
//flush() 之前调用
public
void
preFlush(Iterator entities)
throws
CallbackException {
}
//
flush() 执行SQL语句之后调用
public
void
postFlush(Iterator entities)
throws
CallbackException {
try
{
for
(Iterator it
=
updates.iterator();it.hasNext();){ System.out.println(
"
update=
"
+
it.next() ); }
for
(Iterator it
=
inserts.iterator();it.hasNext();){ System.out.println(
"
insert
"
+
it.next() ); } }
catch
(Exception e) { e.printStackTrace(); } }
public
Boolean isTransient(Object entity) {
//
TODO Auto-generated method stub
return
null
; }
//决定Session中那些对象是脏数据 如果null Session使用默认处理脏数据
public
int
[] findDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState, String[] propertyNames, Type[] types) {
return
null
; }
// 当Session构造实体类对象前调用
public
Object instantiate(String entityName, EntityMode entityMode, Serializable id)
throws
CallbackException {
return
null
; }
public
String getEntityName(Object object)
throws
CallbackException {
//
TODO Auto-generated method stub
return
null
; }
public
Object getEntity(String entityName, Serializable id)
throws
CallbackException {
//
TODO Auto-generated method stub
return
null
; }
public
void
afterTransactionBegin(Transaction tx) {
//
TODO Auto-generated method stub
}
public
void
beforeTransactionCompletion(Transaction tx) {
//
TODO Auto-generated method stub
}
public
void
afterTransactionCompletion(Transaction tx) {
//
TODO Auto-generated method stub
}
}
测试
package
hbn.test.supper.Interceptor;
import
java.lang.reflect.Field;
import
org.hibernate.Session;
import
org.hibernate.SessionFactory;
import
org.hibernate.Transaction;
import
hbn.HibernateSessionFactory;
import
hbn.bean.T2oo;
import
junit.framework.TestCase;
public
class
TestIC
extends
TestCase {
private
SessionFactory sessionFactory;
protected
void
setUp()
throws
Exception {
super
.setUp();
//
利用java反射得到 HibernateSessionFactory ->
//
private static org.hibernate.SessionFactory sessionFactory;
//
要模拟 并发 要 HibernateSessionFactory 得出的 有 threadLocal 不行
HibernateSessionFactory.currentSession(); HibernateSessionFactory.closeSession(); Field field
=
HibernateSessionFactory.
class
.getDeclaredField(
"
sessionFactory
"
); field.setAccessible(
true
); sessionFactory
=
(SessionFactory) field.get(HibernateSessionFactory.
class
); }
public
void
testInc()
throws
Exception { TestInterceptor intx
=
new
TestInterceptor();
//
加载拦截器
Session session
=
sessionFactory.openSession(intx); Transaction tr
=
session.beginTransaction(); T2oo t2
=
new
T2oo(
23
); session.save(t2); t2.setAvg(
new
Integer(
99
)); tr.commit(); } }
结果 Hibernate: insert into t2oo (version, avg, aid, id) values (?, ?, ?, ?) Hibernate: update t2oo set version=?, avg=?, aid=? where id=? and version=? //拦截到的 update=hbn.bean.T2oo@277 inserthbn.bean.T2oo@277
test.xls 中内容 -> <?xml version="1.0"?> <Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet" xmlns:html="http://www.w3.org/TR/REC-html40">
<Worksheet ss:Name="xls1">
<Table> <Row> <Cell><Data ss:Type="String">cell a1</Data></Cell> <Cell><Data ss:Type="String">cell b2</Data></Cell> </Row> <Row> <Cell><Data ss:Type="String">cell a2</Data></Cell> <Cell><Data ss:Type="String">cell b3</Data></Cell> </Row> </Table> </Worksheet>
</Workbook> 展现的样子-> cell a1 | cell b2 | cell a2 | cell b3 |
引用 http://blog.joycode.com/joe/archive/2005/09/06/63068.aspx http://www.itlearner.com/article/2006/3325.shtml使用方法: js
//获得Cookie解码后的值 function GetCookieVal(offset){ var endstr = document.cookie.indexOf (";", offset); if (endstr == -1) endstr = document.cookie.length; return unescape(document.cookie.substring(offset, endstr)); }
//设定Cookie值 function SetCookie(name, value){ var expdate = new Date(); var argv = SetCookie.arguments; var argc = SetCookie.arguments.length; var expires = (argc > 2) ? argv[2] : null; var path = (argc > 3) ? argv[3] : null; var domain = (argc > 4) ? argv[4] : null; var secure = (argc > 5) ? argv[5] : false; if(expires!=null) expdate.setTime(expdate.getTime() + ( expires * 1000 )); document.cookie = name + "=" + escape (value) +((expires == null) ? "" : ("; expires="+ expdate.toGMTString())) +((path == null) ? "" : ("; path=" + path)) +((domain == null) ? "" : ("; domain=" + domain)) +((secure == true) ? "; secure" : ""); }
//删除Cookie function DelCookie(name){ var exp = new Date(); exp.setTime (exp.getTime() - 1); var cval = GetCookie (name); document.cookie = name + "=" + cval + "; expires="+ exp.toGMTString(); }
//获得Cookie的原始值 function GetCookie(name){ var arg = name + "="; var alen = arg.length; var clen = document.cookie.length; var i = 0; while (i < clen) { var j = i + alen; if (document.cookie.substring(i, j) == arg) return GetCookieVal (j); i = document.cookie.indexOf(" ", i) + 1; if (i == 0) break; } return null; }
jsunit <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=BIG5"> <title>x</title> <script type="text/javascript" src="test.js"></script> <script type="text/javascript" src="lib/jsUnitCore.js"></script> <script type="text/javascript"> function testValidArgs() { // 测试的函式要以test名称作为开头 SetCookie('li','gg'); assertEquals("cookie get err", 'gg', GetCookie('li') ); assertEquals("cookie getVal err", 'li=gg', GetCookieVal('li') ); DelCookie("li"); assertEquals("cookie del err ",null, GetCookie('li') ); }
</script> </head> <body> </body> </html>
运行 Jsunit-> testRunner.html 通过测试
环境:
private
SessionFactory sessionFactory;
protected
void
setUp()
throws
Exception {
super
.setUp();
//
利用java反射得到 HibernateSessionFactory ->
//
private static org.hibernate.SessionFactory sessionFactory;
//
要模拟 并发 要 HibernateSessionFactory 得出的 有 threadLocal 不行
//
要
HibernateSessionFactory.currentSession(); HibernateSessionFactory.closeSession(); Field field
=
HibernateSessionFactory.
class
.getDeclaredField(
"
sessionFactory
"
); field.setAccessible(
true
); sessionFactory
=
(SessionFactory) field.get(HibernateSessionFactory.
class
); }
protected
void
tearDown()
throws
Exception {
super
.tearDown(); }
悲观锁:
/**
悲观锁问题 线程模拟 并发 * Table -> T1oo(id,name) * +----+------+ * | id | name | * +----+------+ * | 4 | xx1 | * +----+------+
*/
public
void
ctestLock()
throws
Exception {
//
insert test Data 测试数据
Session seInsert
=
sessionFactory.openSession(); Transaction tr
=
seInsert.beginTransaction(); T1oo testUse
=
testUse
=
new
T1oo(); testUse.setName(
"
liukaiyi_test
"
); seInsert.save(testUse); tr.commit(); System.out.println(
"
**************Test Use Bean : insert*******************
"
); seInsert.close(); Integer testId
=
testUse.getId(); //并发模拟 Session session1
=
sessionFactory.openSession(); Session session2
=
sessionFactory.openSession();
final
Transaction tr1
=
session1.beginTransaction(); Transaction tr2
=
session2.beginTransaction(); Query qu1
=
session1.createQuery(
"
from T1oo t1oo where t1oo.name='liukaiyi_test'
"
); Query qu2
=
session2.createQuery(
"
from T1oo t1oo where t1oo.name='liukaiyi_test'
"
); //加悲观锁 qu1.setLockMode(
"
t1oo
"
,LockMode.UPGRADE);
final
Object bean1
=
qu1.uniqueResult(); Object bean2
=
qu2.uniqueResult();
T1oo t1oo2
=
(T1oo)bean2; t1oo2.setName(
"
run1
"
);
new
Thread(
new
Runnable(){
public
void
run() {
try
{ System.out.println(
"
********解锁准备*********
"
); Thread.sleep(
10
*
1000
); T1oo t1oo1
=
(T1oo)bean1; t1oo1.setName(
"
run2
"
); tr1.commit(); System.out.println(
"
********解锁成功t*********
"
); }
catch
(InterruptedException e) {e.printStackTrace();} } } ).start();
/
/这里会 等待十秒后 tr1解锁 /
tr2.commit(); session1.close(); session2.close();
//
delete Test Date 删除测试数据
Session seDelete
=
sessionFactory.openSession(); Transaction trD
=
seDelete.beginTransaction(); Object obj
=
seDelete.createQuery(
"
from T1oo t where t.id=:id
"
). setInteger(
"
id
"
,testId.intValue()). uniqueResult(); seDelete.delete(obj); trD.commit(); System.out.println(
"
**************Test Use Bean : delete**************
"
); seDelete.close(); }
乐观锁:
/**
乐观锁问题 * Table -> T1oo(id,name) * T2oo.hbn.xml <class> +> optimistic-lock="version" * id下面 +> <version name="version" type="integer" column="version" /> * +---------+---------+------+ * | Field | Type | Null | * +---------+---------+------+ * | id | int(11) | | * | avg | int(11) | | * | aid | int(11) | YES | * | version | int(11) | YES | * +---------+---------+------+ * 注意:要在数据库中多加一列 * mysql> alter table T2OO add version int;
*/
public
void
testOpLock()
throws
Exception{ //添加测试数据 Session session
=
sessionFactory.openSession(); Transaction trI
=
session.beginTransaction(); Connection conn
=
session.connection(); T2oo t2oo
=
new
T2oo(); T1oo t1oo
=
new
T1oo(
"
t1ooOpLock
"
); t1oo.setT2ooSet(
new
HashSet()); t2oo.setAvg(
new
Integer(
23
)); t2oo.setT1oo(t1oo); t1oo.getT2ooSet().add(t2oo); session.save(t2oo); trI.commit(); session.clear(); session.close();
//并发模拟 Session se1
=
sessionFactory.openSession(); Session se2
=
sessionFactory.openSession(); Transaction tr1
=
se1.beginTransaction(); Transaction tr2
=
se2.beginTransaction(); T1oo obj1
=
(T1oo)se1.load(T1oo.
class
,
new
Integer(
1
)); T1oo obj2
=
(T1oo)se2.load(T1oo.
class
,
new
Integer(
1
)); ((T2oo)obj1.getT2ooSet().iterator().next()).setAvg(
new
Integer(
9
)); ((T2oo)obj2.getT2ooSet().iterator().next()).setAvg(
new
Integer(
10
)); tr1.commit();
try
{ tr2.commit(); }
catch
(Exception e) { se2.clear(); tr2.commit();
//
tr2报错
}
finally
{ se1.close(); se2.close(); } //测试数据删除 Session dele
=
sessionFactory.openSession(); Transaction tr
=
dele.beginTransaction(); dele.delete(obj1); tr.commit(); dele.close(); HibernateSessionFactory.closeSession(); }
inverse 使用
说明约定-如:
1.表属性 :T1oo->id,name
T2oo->id,avg,aid(
外键
),version
2.代码过程是:Save->t1oo对象(T1oo 外键 T2oo) T1oo t1oo = new T1oo(); t1oo.setName("xx"); t1oo.setT2ooSet(new HashSet()); T2oo t2oo2 = new T2oo(24); //t2oo2.setT1oo(t1oo); (在下面的本用例表中的第3属性 ) t1oo.getT2ooSet().add(t2oo2);
(在下面的本用例表中的第2属性 )
session.save(t1oo);
3.本例表使用:
T1oo.hbm.xml -> <set name="t2ooSet" inverse="true" cascade = "all" >
(在下面的本用例表中的第1,2属性 )
<key column="aid"/> <one-to-many class="T2oo"/> </set>
T2oo.hbm.xml -> <many-to-one name="t1oo" column="aid" class="T1oo" cascade="all" />
(在下面的本用例表中的第1,2属性 )
结合上面说明得表为:
+-------+-------+-------+----------+----------+ |hbn.xml|inverse|cascade|t1oo->t2oo|t2oo->t1oo| +-------+-------+-------+----------+----------+ | t1oo | true | all | | | +-------+-------+-------+ true | false | | t2oo | | all | | | +-------+-------+-------+----------+----------+
4.执行
Hibernate语句
:
Hibernate: insert into t1oo (name, id) values (?, ?) Hibernate: insert into t2oo (version, avg, aid, id) values (?, ?, ?, ?) 5.结果为: mysql> select * from t2oo; +----+-----+------+---------+ | id | avg | aid | version | +----+-----+------+---------+ | 2 | 24 | NULL | 0 | //主要就是看 aid属性 +----+-----+------+---------+ 1 row in set (0.00 sec)
mysql> select * from t1oo; //
因为
T1oo总是可以 Save 下面就不再提了
+----+------+ | id | name | +----+------+ | 2 | xx | +----+------+ 1 row in set (0.00 sec)
可改项: +-------+-------+-------+----------+----------+ |hbn.xml|inverse|cascade|t1oo->t2oo|t2oo->t1oo| +-------+-------+-------+----------+----------+ | t1oo | 可改4 | 可改2 | | | +-------+-------+-------+ | 可改1 | | t2oo | | 可改3 | | | +-------+-------+-------+----------+----------+
主本: +-------+-------+-------+----------+----------+ |hbn.xml|inverse|cascade|t1oo->t2oo|t2oo->t1oo| +-------+-------+-------+----------+----------+ | t1oo | true | all | | | +-------+-------+-------+ true | true | | t2oo | | all | | | +-------+-------+-------+----------+----------+ Hibernate: insert into t1oo (name, id) values (?, ?) Hibernate: insert into t2oo (version, avg, aid, id) values (?, ?, ?, ?) mysql> select * from t2oo; +----+-----+------+---------+ | id | avg | aid | version | +----+-----+------+---------+ | 1 | 24 | 1 | 0 | +----+-----+------+---------+ 1 row in set (0.00 sec)
改1 +-------+-------+-------+----------+----------+ |hbn.xml|inverse|cascade|t1oo->t2oo|t2oo->t1oo| +-------+-------+-------+----------+----------+ | t1oo | true | all | | | +-------+-------+-------+ true | false | | t2oo | | all | | | +-------+-------+-------+----------+----------+ Hibernate: insert into t1oo (name, id) values (?, ?) Hibernate: insert into t2oo (version, avg, aid, id) values (?, ?, ?, ?) mysql> select * from t2oo; +----+-----+------+---------+ | id | avg | aid | version | +----+-----+------+---------+ | 1 | 24 | NULL| 0 | +----+-----+------+---------+ 1 row in set (0.00 sec)
改2 +-------+-------+-------+----------+----------+ |hbn.xml|inverse|cascade|t1oo->t2oo|t2oo->t1oo| +-------+-------+-------+----------+----------+ | t1oo | true | | | | +-------+-------+-------+ true | true | | t2oo | | all | | | +-------+-------+-------+----------+----------+ Hibernate: insert into t1oo (name, id) values (?, ?)
Empty set (0.00 sec)
改2 改1 +-------+-------+-------+----------+----------+ |hbn.xml|inverse|cascade|t1oo->t2oo|t2oo->t1oo| +-------+-------+-------+----------+----------+ | t1oo | true | | | | +-------+-------+-------+ true | false | | t2oo | | all | | | +-------+-------+-------+----------+----------+ Hibernate: insert into t1oo (name, id) values (?, ?)
Empty set (0.00 sec)
改3
+-------+-------+-------+----------+----------+ |hbn.xml|inverse|cascade|t1oo->t2oo|t2oo->t1oo| +-------+-------+-------+----------+----------+ | t1oo | true | all | | | +-------+-------+-------+ true | true | | t2oo | | | | | +-------+-------+-------+----------+----------+ Hibernate: insert into t1oo (name, id) values (?, ?) Hibernate: insert into t2oo (version, avg, aid, id) values (?, ?, ?, ?) mysql> select * from t2oo; +----+-----+------+---------+ | id | avg | aid | version | +----+-----+------+---------+ | 1 | 24 | 1 | 0 | +----+-----+------+---------+ 1 row in set (0.00 sec)
改3 改2 +-------+-------+-------+----------+----------+ |hbn.xml|inverse|cascade|t1oo->t2oo|t2oo->t1oo| +-------+-------+-------+----------+----------+ | t1oo | true | | | | +-------+-------+-------+ true | true | | t2oo | | | | | +-------+-------+-------+----------+----------+ Hibernate: insert into t1oo (name, id) values (?, ?)
Empty set (0.00 sec)
改3 改1
+-------+-------+-------+----------+----------+ |hbn.xml|inverse|cascade|t1oo->t2oo|t2oo->t1oo| +-------+-------+-------+----------+----------+ | t1oo | true | all | | | +-------+-------+-------+ true | false | | t2oo | | | | | +-------+-------+-------+----------+----------+ Hibernate: insert into t1oo (name, id) values (?, ?) Hibernate: insert into t2oo (version, avg, aid, id) values (?, ?, ?, ?) mysql> select * from t2oo; +----+-----+------+---------+ | id | avg | aid | version | +----+-----+------+---------+ | 1 | 24 | NULL | 0 | +----+-----+------+---------+ 1 row in set (0.00 sec)
改3 改2 改1 +-------+-------+-------+----------+----------+ |hbn.xml|inverse|cascade|t1oo->t2oo|t2oo->t1oo| +-------+-------+-------+----------+----------+ | t1oo | true | | | | +-------+-------+-------+ true | false | | t2oo | | | | | +-------+-------+-------+----------+----------+ Hibernate: insert into t1oo (name, id) values (?, ?) Empty set (0.00 sec)
改4 +-------+-------+-------+----------+----------+ |hbn.xml|inverse|cascade|t1oo->t2oo|t2oo->t1oo| +-------+-------+-------+----------+----------+ | t1oo | false | all | | | +-------+-------+-------+ true | true | | t2oo | | all | | | +-------+-------+-------+----------+----------+ Hibernate: insert into t1oo (name, id) values (?, ?) Hibernate: insert into t2oo (version, avg, aid, id) values (?, ?, ?, ?) Hibernate: update t2oo set aid=? where id=? mysql> select * from t2oo; +----+-----+------+---------+ | id | avg | aid | version | +----+-----+------+---------+ | 1 | 24 | 1 | 0 | +----+-----+------+---------+ 1 row in set (0.02 sec)
改4 改1 +-------+-------+-------+----------+----------+ |hbn.xml|inverse|cascade|t1oo->t2oo|t2oo->t1oo| +-------+-------+-------+----------+----------+ | t1oo | false | all | | | +-------+-------+-------+ true | false | | t2oo | | all | | | +-------+-------+-------+----------+----------+ Hibernate: insert into t1oo (name, id) values (?, ?) Hibernate: insert into t2oo (version, avg, aid, id) values (?, ?, ?, ?) Hibernate: update t2oo set aid=? where id=? mysql> select * from t2oo; +----+-----+------+---------+ | id | avg | aid | version | +----+-----+------+---------+ | 1 | 24 | 1 | 0 | +----+-----+------+---------+ 1 row in set (0.00 sec)
改4 改2 +-------+-------+-------+----------+----------+ |hbn.xml|inverse|cascade|t1oo->t2oo|t2oo->t1oo| +-------+-------+-------+----------+----------+ | t1oo | false | | | | +-------+-------+-------+ true | true | | t2oo | | all | | | +-------+-------+-------+----------+----------+ Hibernate: insert into t1oo (name, id) values (?, ?) Hibernate: update t2oo set aid=? where id=? Empty set (0.00 sec)
改4 改3 +-------+-------+-------+----------+----------+ |hbn.xml|inverse|cascade|t1oo->t2oo|t2oo->t1oo| +-------+-------+-------+----------+----------+ | t1oo | false | all | | | +-------+-------+-------+ true | true | | t2oo | | | | | +-------+-------+-------+----------+----------+ Hibernate: insert into t1oo (name, id) values (?, ?) Hibernate: insert into t2oo (version, avg, aid, id) values (?, ?, ?, ?) Hibernate: update t2oo set aid=? where id=? mysql> select * from t2oo; +----+-----+------+---------+ | id | avg | aid | version | +----+-----+------+---------+ | 1 | 24 | 1 | 0 | +----+-----+------+---------+ 1 row in set (0.00 sec)
改4 改3 改2 +-------+-------+-------+----------+----------+ |hbn.xml|inverse|cascade|t1oo->t2oo|t2oo->t1oo| +-------+-------+-------+----------+----------+ | t1oo | false | | | | +-------+-------+-------+ true | true | | t2oo | | | | | +-------+-------+-------+----------+----------+ Hibernate: insert into t1oo (name, id) values (?, ?) Hibernate: update t2oo set aid=? where id=? Empty set (0.00 sec)
改4 改1 改2 +-------+-------+-------+----------+----------+ |hbn.xml|inverse|cascade|t1oo->t2oo|t2oo->t1oo| +-------+-------+-------+----------+----------+ | t1oo | false | | | | +-------+-------+-------+ true | false | | t2oo | | all | | | +-------+-------+-------+----------+----------+ Hibernate: insert into t1oo (name, id) values (?, ?) Hibernate: update t2oo set aid=? where id=?
Empty set (0.00 sec)
改4 改1 改3 +-------+-------+-------+----------+----------+ |hbn.xml|inverse|cascade|t1oo->t2oo|t2oo->t1oo| +-------+-------+-------+----------+----------+ | t1oo | false | all | | | +-------+-------+-------+ true | false | | t2oo | | | | | +-------+-------+-------+----------+----------+ Hibernate: insert into t1oo (name, id) values (?, ?) Hibernate: insert into t2oo (version, avg, aid, id) values (?, ?, ?, ?) Hibernate: update t2oo set aid=? where id=? mysql> select * from t2oo; +----+-----+------+---------+ | id | avg | aid | version | +----+-----+------+---------+ | 1 | 24 | 1 | 0 | +----+-----+------+---------+ 1 row in set (0.02 sec)
改4 改3 改2 改1 +-------+-------+-------+----------+----------+ |hbn.xml|inverse|cascade|t1oo->t2oo|t2oo->t1oo| +-------+-------+-------+----------+----------+ | t1oo | false | | | | +-------+-------+-------+ true | false | | t2oo | | | | | +-------+-------+-------+----------+----------+ Hibernate: insert into t1oo (name, id) values (?, ?) Hibernate: update t2oo set aid=? where id=? Empty set (0.00 sec)
缓存问题:
/**
使用 Query.executeUpdate() 缓存中数据不同步 解决办法 * Table -> T1oo(id,name) * Table -> T2oo(id,avg,aid) * 外键 T1oo.id->T2oo.aid * Session.createQuery("delete T1oo") -> Query.executeUpdate()
*/
public
void
testExecuteUpdate(){ System.out.println(
"
\r\n\r\n********************ExecuteUpdate************************
"
); T1oo t1oo
=
new
T1oo(); t1oo.setName(
"
liukaiyi
"
); HibernateSessionFactory.closeSession(); Session session
=
HibernateSessionFactory.currentSession(); Transaction tr1
=
session.beginTransaction();
//
t1 成为 持久状态 一级缓存中 加载
session.saveOrUpdate(t1oo);
//
直接一条语句删除T1oo,缓存无法同步
//
一级缓存中还有 t1
Query qu
=
session.createQuery(
"
delete T1oo
"
);
try
{ qu.executeUpdate(); }
catch
(Exception e) { System.out.println(
"
//err: 有级联 单使用 delete T1oo 还要delete T2oo.aid = T1oo.id//
"
); List list
=
session.createQuery(
"
from T1oo
"
).list();
for
(Iterator it
=
list.iterator();it.hasNext();){ Query t2qu
=
session.createQuery(
"
delete T2oo where aid=:id
"
); t2qu.setInteger(
"
id
"
, ((T1oo)it.next()).getId().intValue()); t2qu.executeUpdate(); } qu.executeUpdate(); } tr1.commit(); Transaction tr2
=
session.beginTransaction();
//
这直接通过一级缓存中加载t2,但DB中以没有此条数据
t1oo
=
(T1oo)session.load(T1oo.
class
,t1oo.getId()); t1oo.setName(
"
google
"
);
try
{ tr2.commit(); }
catch
(Exception e) { System.out.println(
"
//err: update(t1oo)->DB 中数据库中没有 t1oo //
"
); }
System.out.println(
"
一级缓存清空前
"
+
session.get(T1oo.
class
,t1oo.getId()) ); session.evict(t1oo); System.out.println(
"
一级缓存清空后
"
+
session.get(T1oo.
class
,t1oo.getId()) );
//
不把t1oo id 为空,否则当在saveOrUpdate时候就会以为是游离态 update了
t1oo.setId(
null
);
//
id=null insert 调用
session.saveOrUpdate(t1oo); tr2.commit(); Transaction tr3
=
session.beginTransaction(); session.delete(t1oo); tr3.commit(); session.close(); HibernateSessionFactory.closeSession(); }
结果是: ********************ExecuteUpdate************************ log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment). log4j:WARN Please initialize the log4j system properly. Hibernate: insert into t1oo (name, id) values (?, ?) Hibernate: delete from t1oo //err: 有级联 单使用 delete T1oo 还要delete T2oo.aid = T1oo.id// Hibernate: select t1oo0_.id as id, t1oo0_.name as name0_ from t1oo t1oo0_ Hibernate: delete from t2oo where aid=? Hibernate: delete from t2oo where aid=? Hibernate: delete from t2oo where aid=? Hibernate: delete from t1oo Hibernate: update t1oo set name=? where id=? //err: update(t1oo)->DB 中数据库中没有 t1oo // 一级缓存清空前 hbn.bean.T1oo@287 Hibernate: select t1oo0_.id as id0_, t1oo0_.name as name0_0_ from t1oo t1oo0_ where t1oo0_.id=? 一级缓存清空后 null Hibernate: insert into t1oo (name, id) values (?, ?) Hibernate: delete from t1oo where id=?
Get Load 区别 : /** Get Load 区别 (在commit前要 session.flush()) * Table -> T1oo(id,name) * 1.如果未能发现符合条件的记录,get方法返回null,而load方法会抛出异常 * 2.Load方法可返回实体的代理类实例,而get方法永远直接返回实体类。 * 3.load方法可以充分利用内部缓存和二级缓存中的现有数据,而get方法则仅仅在内部缓存中进行数据查找, * 如没有发现对应数据,将越过二级缓存,直接调用SQL完成数据读取。 */ public void testGetLoad() throws Exception { System.out.println("\r\n\r\n********************Get<>Load************************"); Session session = HibernateSessionFactory.currentSession(); // 数据准备 T1oo t1oo = new T1oo(); t1oo.setName("liu"); Transaction t1 = session.beginTransaction(); session.saveOrUpdate(t1oo); // 为什么这会错? //session.evict(t1oo); //session.flush(); t1.commit(); session.evict(t1oo); Transaction t2 = session.beginTransaction(); System.out.println("一级缓存是否有t1oo(load)->"+session.contains(t1oo)); //这时候t1oo为 CGlib生成的代理类 t1oo = (T1oo)session.load(T1oo.class,t1oo.getId()); System.out.println(" 延迟加载出现:select.. t1oo0_.id=? 表的其他属性加载 "); t1oo.setName("load list"); //后在 update t2.commit(); session.evict(t1oo); Transaction t3 = session.beginTransaction(); System.out.println("一级缓存是否有t1oo(get)->"+session.contains(t1oo)); //这时候t1oo为 CGlib生成的代理类 t1oo = (T1oo)session.get(T1oo.class,t1oo.getId()); System.out.println(" 没有延迟加载出现"); t1oo.setName("get list"); //后在 update t3.commit(); session.evict(t1oo); Transaction tr3 = session.beginTransaction(); session.delete(t1oo); tr3.commit(); session.close(); HibernateSessionFactory.closeSession(); }
结果 ********************Get<>Load************************ Hibernate: insert into t1oo (name, id) values (?, ?) 一级缓存是否有t1oo(load)->false 延迟加载出现:select.. t1oo0_.id=? 表的其他属性加载 Hibernate: select t1oo0_.id as id0_, t1oo0_.name as name0_0_ from t1oo t1oo0_ where t1oo0_.id=? Hibernate: update t1oo set name=? where id=? 一级缓存是否有t1oo(get)->false Hibernate: select t1oo0_.id as id0_, t1oo0_.name as name0_0_ from t1oo t1oo0_ where t1oo0_.id=? 没有延迟加载出现 Hibernate: update t1oo set name=? where id=? Hibernate: select t2ooset0_.aid as aid1_, t2ooset0_.id as id1_, t2ooset0_.id as id0_, t2ooset0_.avg as avg1_0_, t2ooset0_.aid as aid1_0_ from t2oo t2ooset0_ where t2ooset0_.aid=? Hibernate: delete from t1oo where id=?
Set 集合的识别:
/** Set 集合的识别 * Table -> T1oo(id,name) * Table -> T2oo(id,avg,aid) * 外键 T1oo.id->T2oo.aid * T1oo <set name="t2ooSet" inverse="false" cascade = "all" > * T2oo <many-to-one name="t1oo" column="aid" class="T1oo" /> * cascade='insert' 是一定要的 * 当 T1oo没有 inverse="true" 主动权的时候,要双项关联 * t1oo.getT2ooSet().add(t2oo1); * t1oo.getT2ooSet().add(t2oo2); * t2oo1.setT1oo(t1oo); * t2oo2.setT1oo(t1oo); * 要不后sql为: * Hibernate: insert into t2oo (avg, aid, id) values (?, ?, ?) * Hibernate: insert into t2oo (avg, aid, id) values (?, ?, ?) * +----+-----+------+ * | id | avg | aid | * +----+-----+------+ * | 1 | 24 | NULL | * | 2 | 23 | NULL | * +----+-----+------+ * 当 T1oo有 inverse="false"主动权的时候 * t1oo.getT2ooSet().add(t2oo1); * t1oo.getT2ooSet().add(t2oo2); * Sql语句为: * Hibernate: insert into t1oo (name, id) values (?, ?) * Hibernate: insert into t2oo (avg, aid, id) values (?, ?, ?) * Hibernate: insert into t2oo (avg, aid, id) values (?, ?, ?) * Hibernate: update t2oo set aid=? where id=? * Hibernate: update t2oo set aid=? where id=? * | 3 | 24 | 12 | * | 4 | 23 | 12 | * +----+-----+------+ */ public void testSet(){ System.out.println("\r\n\r\n********************Set************************"); T1oo t1oo = new T1oo(); t1oo.setName("list"); T2oo t2oo1 = new T2oo(); t2oo1.setAvg(new Integer(23)); T2oo t2oo2 = new T2oo(); t2oo2.setAvg(new Integer(24)); Session session = HibernateSessionFactory.currentSession(); Transaction tr1 = session.beginTransaction(); session.save(t1oo); t1oo = (T1oo) session.load(T1oo.class,t1oo.getId());
t1oo.setT2ooSet(new HashSet()) ; t1oo.getT2ooSet().add(t2oo1); t1oo.getT2ooSet().add(t2oo2); System.out.println( t1oo.getT2ooSet().size()+"" ); tr1.commit(); System.out.println(); T2oo t2oo3 = new T2oo(); t2oo3.setAvg(new Integer(25)); T1oo t1oo2 = new T1oo(); t1oo2.setName("mz"); t2oo3.setT1oo(t1oo2); Transaction tr2 = session.beginTransaction(); session.save(t2oo3); try { tr2.commit(); } catch (Exception e) { System.out.println("//err: 没有主动权 cascade = 'all' 不可以级联save t1oo //"); } session.close(); HibernateSessionFactory.closeSession(); }
结果是: ********************Set************************ 2 Hibernate: insert into t1oo (name, id) values (?, ?) Hibernate: insert into t2oo (avg, aid, id) values (?, ?, ?) Hibernate: insert into t2oo (avg, aid, id) values (?, ?, ?) Hibernate: update t2oo set aid=? where id=? Hibernate: update t2oo set aid=? where id=?
//err: 没有主动权 cascade = 'all' 不可以级联save t1oo //
学习: http://visualjquery.com/1.1.2.htmlDOM Attributes 1.attr(key, value) $("img").attr("title", "xx"); 也是对属性的添加但可以动态 eg: 在每次给title时 动态了开始 <img title="pic" /><img title="pic" /><img title="pic" /> 通过$("img").attr("title", function(index) { return this.title + (i + 1); }); <img title="pic 1" /><img title="pic 2" /><img title="pic 3" /> 2. html 内容取、赋值 取 <div><input/></div> ->> $("div").html(); ->> 结果:<input/> 赋 $("div").html("<b>new stuff</b>"); ->><div><b>new stuff</b></div> 通过这 ajax 就很简单了。^_^ Manipulation1.位置调换 after, append、before $("p").after("<b>Hello</b>"); <p>后 添加 <b>.. $("p").after( $("#foo")[0] ); 把id为foo的标签移动到<p>后 $("input[@name='butt1']").clone().prependTo("form"); //clone in form
参考: http://visualjquery.com/1.1.2.html
1.定位
$( 'xx' )
$("p[a]").hide(); $("p:eq(0)").show(); $("div:visible").hide(); $("ul/li") /* valid too: $("ul > li") */ $("p.foo[a]"); $("input[@name=bar]").val(); $("input[@type=radio][@checked]")
2.事件添加
<a href="#" name="li" >Link</a>
$(document).ready(function() { $("a").click(function() { $("div").hide(); //跌代不可见 <a> }); }); 3.页面 javascript 输入(和jsp的 out.print(...))$(html)
$("<div id='div1'><font color='red''>Hello</font></div>").appendTo("body"); 4.写css
$(document.body).css( "background", "black" ); 5.包含定位
<p>one</p> <div><p>two</p></div> <div>three</div>
$("div > p") //定位two <p>two</p>
6.范围定位
<body> <form> <input type="button" value="哈哈"/> </form> </body>
$("input:button", document.forms[0])[0].setAttribute("value","google"); 或 $("div", xml.responseXML) 等
7.表达试定位$("p[@name='p1']").hide();//hide不要 $(..)[0]
$("input[@name='butt1']:button", document.forms[0])[0].setAttribute("value","google"); 8.$(..).fun.. 添加方法
<form> <input name="butt1" type="button" value="google"/> </form> <script> jQuery.fn.extend({ check: function() { alert('check'); } }); $("input[@name='butt1']:button", document.forms[0]).check(); </script>
或
jQuery.extend({ min: function(a, b) { return a < b ? a : b; }, max: function(a, b) { return a > b ? a : b; } });
9.$.noConflict() <body> <form> <input name="butt1" type="button" value="google"/> </form> <a href="#" temp_href="#" name="li" >Link</a> <script> var $j = jQuery.noConflict(); // Use jQuery via $j() $j(document).ready(function(){ $("a").click(function() { $j(document.forms[0]).hide(); }); }); </script> </body> 10. $ 一般方法
//each(fn)$("img").each(function(i){ this.src = "test" + i + ".jpg"; }); <img/><img/> <img src="test0.jpg"/><img src="test1.jpg"/>
$("p").eq(1) //后1个 $("p").lt(1) //正取 1 开始
$("img").get();//全取 $("img").get(0); //顺序取 0开始 $("p").gt(0) //反取从0开始
$("*").index( $('#foo')[0] ) <div id="foobar"><b></b><span id="foo"></span></div> 返回结果 2
$("img").length; //总长度 $("img").size();
直接看代码.. dom4j 的一般使用都在里面了 /lib/dom4j-1.6.1.jar /lib/jaxen-1.1-beta-6.jar package useDom4j.test.supper;
import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URL; import java.util.Iterator; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern;
import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory;
import junit.framework.TestCase;
import org.dom4j.Document; import org.dom4j.DocumentFactory; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.Node; import org.dom4j.QName; import org.dom4j.Visitor; import org.dom4j.VisitorSupport; import org.dom4j.XPath; import org.dom4j.io.DOMReader; import org.dom4j.io.HTMLWriter; import org.dom4j.io.OutputFormat; import org.dom4j.io.SAXReader; import org.dom4j.io.XMLWriter;
public class useDom4jTest extends TestCase {
//use all private String path ; private ClassLoader clo; // file path -> bin private String classPath ; //use save static private Document doc; private String filese;
protected void setUp() throws Exception { super.setUp(); path = "useDom4j/test/config/test.xml"; clo = this.getClass().getClassLoader(); classPath = System.getProperty("java.class.path").split(";")[0] ; filese = System.getProperty("file.separator"); }
protected void tearDown() throws Exception { super.tearDown(); }
public void testRead()throws Exception{ SAXReader sax = new SAXReader(); //File read Document docF = sax.read( new File(clo.getResource(path).getFile()) ); assertNotNull("is File saxReader err",docF); //InPutStream read Document docI = sax.read( clo.getResourceAsStream(path) ); assertNotNull("is InPutStream saxReader err",docI); //URL read Document docU = sax.read( clo.getResource(path) ); assertNotNull("is Url saxReader err",docU); } /** converts a W3C DOM document into a dom4j document */ public void testConversion() throws Exception{ DocumentBuilderFactory domfac=DocumentBuilderFactory.newInstance(); DocumentBuilder dombuilder=domfac.newDocumentBuilder(); InputStream input = clo.getResourceAsStream(path) ; org.w3c.dom.Document doc3c = dombuilder.parse( input ); DOMReader xmlReader = new DOMReader(); assertEquals( " Conversion : W3C DOM-> dom4j DOM err", xmlReader.read(doc3c) instanceof Document,true ); } public void testCreate()throws Exception{ DocumentFactory factory = DocumentFactory.getInstance(); doc = factory.createDocument(); //root Create Element root = doc.addElement("testElement"); assertNotNull("is root Create err",root); Element author2 = root.addElement( "author" ) .addAttribute( "name", "Toby" ) .addAttribute( "location", "Germany" ) .addText( "Tobias Rademacher" );
Element author1 = root.addElement( "author" ) .addAttribute( "name", "James" ) .addAttribute( "location", "UK" ) .addText( "James Strachan" ); //Test Create //use XPath ->jaxen-xxx.jar assertEquals("create Element author2 err", doc.selectSingleNode("/testElement/author[@name='Toby']").getText() ,"Tobias Rademacher"); assertEquals("create Element author1 err", doc.selectSingleNode("/testElement/author[@location='UK']/@name").getText() ,"James"); }
public void testPrintingHTML()throws Exception{ String testSaveXml = "useDom4j/test/config/testHtml.html"; testSaveXml = classPath+filese+testSaveXml; File file = getFile(testSaveXml); //Save file.html HTMLWriter writer = new HTMLWriter(new FileOutputStream( file )); writer.write(new SAXReader().read( clo.getResource(path) )); writer.flush(); } public void testIterator(){ Element root = this.doc.getRootElement(); //Iterator Iterator elementIterator = root.elementIterator(); while(elementIterator.hasNext()){ Element element = (Element)elementIterator.next(); assertNotNull("not attr name", element.selectSingleNode("./@name") ); assertNotNull("not attr location", element.selectSingleNode("./@location") ); assertNotNull("not Text ", element.selectSingleNode(".").getText() ); } //for -> ./XX for ( int i = 0, size = root.nodeCount(); i < size; i++ ) { Node node = root.node(i); if ( node instanceof Element ) { Element element = (Element)node; assertNotNull("not attr name", element.selectSingleNode("./@name") ); assertNotNull("not attr location", element.selectSingleNode("./@location") ); assertNotNull("not Text ", element.selectSingleNode(".").getText() ); } } //List List elements = root.elements(); int size = elements.size() ; if ( size > 4 ) { elements.subList( 3, 4 ).clear(); assertEquals("List is not clear",size-elements.size()==1,true); }
} /** use test.xml test xpath -> /project/organization/ <organization> <name>MetaStuff Ltd.</name> <url>http://sourceforge.net/projects/dom4j</url> <logo>http://sourceforge.net/sflogo.php?group_id=16035</logo> </organization> xpath -> /project/dependencies/dependency[groupId='msv'] <dependency> <groupId>msv</groupId> <artifactId>xsdlib</artifactId> <version>20030807</version> <url>https://msv.dev.java.net/</url> </dependency> */ public void testXpath()throws Exception{ XPath xpathSelector = DocumentHelper.createXPath("/project/organization/*"); Document docT = new SAXReader().read( clo.getResourceAsStream(path) ); List results = xpathSelector.selectNodes(docT); for ( Iterator iter = results.iterator(); iter.hasNext(); ) { Element element = (Element) iter.next(); if(element.getName().equals("name")){ assertEquals("name err", element.getText().equals("MetaStuff Ltd."),true); } if(element.getName().equals("url")){ assertEquals("url err", element.getText().equals("http://sourceforge.net/projects/dom4j"),true); } if(element.getName().equals("logo")){ assertEquals("logo err", element.getText().equals("http://sourceforge.net/sflogo.php?group_id=16035"),true); } } // select String url = docT.valueOf( "/project/dependencies/dependency[groupId='msv']/url" ); assertEquals("Url err", url.equals("https://msv.dev.java.net/"),true); Number count = docT.numberValueOf( "/project/dependencies/dependency[groupId='msv']/version" ); assertEquals("Url err", count.intValue()==20030807,true); }
public void testVisitor(){ Visitor visitor = new VisitorSupport() { public void visit(Element element) { System.out.println( "Entity name: " + element.getName() + " text :" + element.getText() ); } };
doc.accept( visitor ); }
// element.clone ; element.createCopy ; public void testInsertElementAt() throws Exception{ Element root = this.doc.getRootElement(); Element oldElement = (Element)doc.selectSingleNode("/testElement/author[@name='Toby']"); Element newElement = (Element) oldElement.clone(); List list = root.content(); list.add( root.indexOf(oldElement)+1,newElement );
} public void testSave()throws Exception{ String testSaveXml = "useDom4j/test/config/testSave.xml"; testSaveXml = classPath+filese+testSaveXml; File file = getFile(testSaveXml); //Save file.xml XMLWriter writer = new XMLWriter(new FileOutputStream( file )); writer.write(doc); writer.flush(); }
private File getFile(String testSaveXml) throws IOException { File file = null ; URL url = clo.getResource(testSaveXml); if(url==null){ file = new File(testSaveXml); file.createNewFile(); }else{ file = new File( url.getFile() ); } return file; } }
引用:http://freezingxu.blog.com.cn/archives/2006/1892647.shtml /** * 对指定的节点增加属性和文本 * @param elmt * @param name * @param value * @param text * @return */ public Element addAttribute(Element elmt,String name,String value){ elmt.addAttribute(name,value); return elmt; } /** * 修改指定节点的属性和文本 * @param elmt * @param name * @param value * @param text * @return */ public Element setAttribute(Element elmt,String name,String value){ Attribute attribute = elmt.attribute(name); //attribute.setName(name); attribute.setValue(value); List list = new ArrayList(); list.add(attribute); elmt.setAttributes(list); return elmt; } /** * 删除指定节点的指定属性 * @param elmt * @param name * @return */ public Element removeAttribute(Element elmt,String name){ elmt.remove(elmt.attribute(name)); return elmt; } /** * 输出为文件 * @param doc * @throws IOException */ public void writeFile(Document doc) throws IOException{ FileWriter out = new FileWriter( "d:/newQuery.xml" ); doc.write(out); out.flush(); out.close(); }
看hbn 源代码 发现用了 CGlib 这就看看这个jar 。特留个文 ^_^(转)http://www.nirvanastudio.org/java/cglib-%E6%8C%87%E5%8D%97.html
CGlib 就2个例能说明一切 先是使用类 public class MyClass { public void method() { System.out.println("MyClass.method()"); }
public void method2() { System.out.println("MyClass.method2()"); } }
例1: import java.lang.reflect.Method; import net.sf.cglib.proxy.Enhancer; import net.sf.cglib.proxy.MethodProxy; import net.sf.cglib.proxy.MethodInterceptor; public class Main { public static void main(String[] args) { Enhancer enhancer = new Enhancer(); //在这代理了 enhancer.setSuperclass(MyClass.class); enhancer.setCallback( new MethodInterceptorImpl() ); // 创造 代理 (动态扩展了MyClass类) MyClass my = (MyClass)enhancer.create(); my.method(); } private static class MethodInterceptorImpl implements MethodInterceptor { public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable { System.out.println(method); proxy.invokeSuper(obj, args); return null; } } } 例2: import java.lang.reflect.Method;
import net.sf.cglib.proxy.Enhancer; import net.sf.cglib.proxy.MethodProxy; import net.sf.cglib.proxy.MethodInterceptor; import net.sf.cglib.proxy.NoOp; import net.sf.cglib.proxy.Callback; import net.sf.cglib.proxy.CallbackFilter; public class Main2 { public static void main(String[] args) { Callback[] callbacks = new Callback[] { new MethodInterceptorImpl(), NoOp.INSTANCE }; Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(MyClass.class); enhancer.setCallbacks( callbacks ); //添加 方法过滤器 返回1为不运行 2 为运行 enhancer.setCallbackFilter( new CallbackFilterImpl() ); MyClass my = (MyClass)enhancer.create(); my.method(); my.method2(); } private static class CallbackFilterImpl implements CallbackFilter { public int accept(Method method) { if ( method.getName().equals("method2") ) { return 1; } else { return 0; } } } private static class MethodInterceptorImpl implements MethodInterceptor { public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable { System.out.println(method); return proxy.invokeSuper(obj, args); } } } 简单不 哈哈 比jdk 中的动态代理好用 ,那还要接口 不太方便 。
参照: 容器外的JSP页面测试技术由于上面给出例 复杂 。一般人很难理解。我也是 ^_^ 但仔细看我还是自己写出一个比较简单的,望大家一起讨论。 被测试jsp
<%@ taglib prefix="html" uri="/WEB-INF/struts-html.tld" %> <%@ taglib prefix="c" uri="/WEB-INF/c-1_0-rt.tld" %> <html:html> <c:if test="${name != pass}"> ${name} <br> ${pass} <br> <!-- <html:text property="in" ></html:text> --> </c:if> </html:html>
ant直接把他放在 eclipes 工程的根目录下 build.xml 但有有3个参数要设置 tomcat.home Tomcat 的地址 webapp.path 工程中的根目录,下面有WEB-INF src 原代码 (到时候jsp会翻译成.java 到这个目录的 org.apache.jsp.jsp 下)
<project name="Webapp Precompilation" default="all" basedir=".">
<!-- tomcat dir --> <property name="tomcat.home" value="D:\Tomcat 5.0"/> <!-- this=..//WEB-INF (in eclipes) --> <property name="webapp.path" value=".\WebRoot"/> <!-- src (in eclipes) --> <property name="src" value="./src"/>
<target name="jspc"> <taskdef classname="org.apache.jasper.JspC" name="jasper2" > <classpath id="jspc.classpath"> <pathelement location="${java.home}/../lib/tools.jar"/> <fileset dir="${tomcat.home}/bin"> <include name="*.jar"/> </fileset> <fileset dir="${tomcat.home}/server/lib"> <include name="*.jar"/> </fileset> <fileset dir="${tomcat.home}/common/lib"> <include name="*.jar"/> </fileset> </classpath> </taskdef>
<jasper2 validateXml="false" uriroot="${webapp.path}" webXmlFragment="${webapp.path}/WEB-INF/generated_web.xml" outputDir="${src}" /> </target>
<target name="compile">
<mkdir dir="${webapp.path}/WEB-INF/classes"/> <mkdir dir="${webapp.path}/WEB-INF/lib"/>
<javac destdir="${webapp.path}/WEB-INF/classes" optimize="off" debug="on" failonerror="false" srcdir="${src}" excludes="**/*.smap"> <classpath> <pathelement location="${webapp.path}/WEB-INF/classes"/> <fileset dir="${webapp.path}/WEB-INF/lib"> <include name="*.jar"/> </fileset> <pathelement location="${tomcat.home}/common/classes"/> <fileset dir="${tomcat.home}/common/lib"> <include name="*.jar"/> </fileset> <pathelement location="${tomcat.home}/shared/classes"/> <fileset dir="${tomcat.home}/shared/lib"> <include name="*.jar"/> </fileset> <fileset dir="${tomcat.home}/bin"> <include name="*.jar"/> </fileset> </classpath> <include name="**" /> <exclude name="tags/**" /> </javac>
</target>
<target name="all" depends="jspc,compile"> </target>
<target name="cleanup"> <delete> <fileset dir="${webapp.path}/WEB-INF/src"/> <fileset dir="${webapp.path}/WEB-INF/classes/org/apache/jsp"/> </delete> </target>
</project> TEST
package jetty.test.supper;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;
import org.apache.jsp.jsp.MyJsp_jsp;
import com.meterware.httpunit.GetMethodWebRequest; import com.meterware.httpunit.WebRequest; import com.meterware.httpunit.WebResponse; import com.meterware.servletunit.InvocationContext; import com.meterware.servletunit.ServletRunner; import com.meterware.servletunit.ServletUnitClient;
import junit.framework.TestCase;
public class JSPCTest extends TestCase{ private InvocationContext ic = null ;
protected void setUp() throws Exception { ServletRunner sr = new ServletRunner(); // 向环境中注册 jsp sr.registerServlet("HelloWorld", MyJsp_jsp.class.getName()); ServletUnitClient sc = sr.newClient(); WebRequest request = new GetMethodWebRequest("http://localhost/HelloWorld"); ic = sc.newInvocation(request);
} public void testJspC() throws Exception{ HttpServletRequest re = ic .getRequest(); HttpServletResponse rq = ic.getResponse(); re.setAttribute("name","liukaiyi"); re.setAttribute("pass","123456"); MyJsp_jsp is = (MyJsp_jsp) ic.getServlet(); is._jspService(re,rq); WebResponse response = ic.getServletResponse(); // 输出 System.out.println( response.getText() ); } } 结果是
<html> liukaiyi <br> 123456 <br> </html>
后面用 HttpUnit 和 HtmlUnit 测试就不用我说了把 网上一大把。
学习测试留个印
测试 Servlet 使用:
package
jetty.test.supper;
import
java.io.File;
import
javax.servlet.http.HttpServletRequest;
import
jetty.LoginServlet;
import
com.meterware.httpunit.GetMethodWebRequest;
import
com.meterware.httpunit.WebConversation;
import
com.meterware.httpunit.WebRequest;
import
com.meterware.httpunit.WebResponse;
import
com.meterware.servletunit.InvocationContext;
import
com.meterware.servletunit.ServletRunner;
import
com.meterware.servletunit.ServletUnitClient;
import
junit.framework.TestCase;
public
class
HttpUnitTest
extends
TestCase {
public
void
ctestUrl()
throws
Exception{ System.out.println(
"
直接获取网页内容:
"
); WebConversation wc
=
new
WebConversation(); WebResponse wr
=
wc.getResponse(
"
http://www.google.com
"
); System.out.println( wr.getText() ); }
public
void
testRun1()
throws
Exception{ System.out.println(
"
无参数测试:
"
);
//
建立服务器
ServletRunner sr
=
new
ServletRunner(
new
File(
"
WebRoot\\WEB-INF\\test.xml
"
));
//
模拟客户端
ServletUnitClient sc
=
sr.newClient();
//
URL 定位
WebRequest request
=
new
GetMethodWebRequest(
"
http://localhost:7000/cactusDemo
"
); WebResponse response
=
sc.getResponse( request );
//
运行
System.out.println(response.getText()
+
"
\n
"
); }
public
void
testRun2()
throws
Exception{ System.out.println(
"
Session 和 request 测试:
"
); ServletRunner sr
=
new
ServletRunner(
new
File(
"
WebRoot\\WEB-INF\\test.xml
"
)); ServletUnitClient sc
=
sr.newClient(); WebRequest request
=
new
GetMethodWebRequest(
"
http://localhost/cactusDemo
"
);
//
Parameter 加参 use
request.setParameter(
"
use
"
,
"
web
"
);
//
取出 Servlet : LoginServlet 方法准备执行
InvocationContext ic
=
sc.newInvocation( request ); LoginServlet se
=
(LoginServlet)ic.getServlet(); HttpServletRequest re
=
ic.getRequest() ;
//
request session 加参 use
re.setAttribute(
"
use
"
,
"
re
"
); re.getSession(
true
).setAttribute(
"
use
"
,
"
re
"
);
se.doGet(re,ic.getResponse());
//
关键:运行测试方法
//
获取 out
WebResponse response
=
ic.getServletResponse(); System.out.println(response.getText()); } }
test.xml
<?
xml version="1.0" encoding="UTF-8"
?>
<
web-app
xmlns
="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi
="http://www.w3.org/2001/XMLSchema-instance"
version
="2.4"
xsi:schemaLocation
="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
>
<
servlet
>
<
servlet-name
>
cactusDemo
</
servlet-name
>
<
servlet-class
>
jetty.LoginServlet
</
servlet-class
>
</
servlet
>
<
servlet-mapping
>
<
servlet-name
>
cactusDemo
</
servlet-name
>
<
url-pattern
>
/cactusDemo
</
url-pattern
>
</
servlet-mapping
>
</
web-app
>
测试 JSP:
Cookbook
参考
不使用容器 进行 测试 jsp
测试Struts:
StrutsTestCase
参考
1. HttpUnit 1>servlet可以脱离容器,容易把该测试写入ant或maven脚本,让测试进行。 2>httpunit在测试servlet行为时,采用的是完全模拟浏览器,有时测试比较难写。 package Cactus.test.support;
import junit.framework.TestCase; import Cactus.HelloWorld;
import com.meterware.httpunit.GetMethodWebRequest; import com.meterware.httpunit.WebRequest; import com.meterware.httpunit.WebResponse; import com.meterware.servletunit.InvocationContext; import com.meterware.servletunit.ServletRunner; import com.meterware.servletunit.ServletUnitClient; import junit.framework.Assert; public class HttpUnitTestHelloWorld extends TestCase { protected void setUp() throws Exception { super.setUp(); } protected void tearDown() throws Exception { super.tearDown(); } public void testHelloWorld() { try {
// 创建Servlet的运行环境 ServletRunner sr = new ServletRunner(); // 向环境中注册Servlet sr.registerServlet("HelloWorld", HelloWorld.class.getName()); // 创建访问Servlet的客户端 ServletUnitClient sc = sr.newClient();
// 发送请求 WebRequest request = new GetMethodWebRequest("http://localhost/HelloWorld"); request.setParameter("username", "testuser"); //用委托加载 is InvocationContext ic = sc.newInvocation(request); HelloWorld is = (HelloWorld) ic.getServlet(); // 测试servlet的某个方法 Assert.assertTrue(is.authenticate());
// 获得模拟服务器的信息 WebResponse response = sc.getResponse(request);
// 断言 Assert.assertTrue(response.getText().equals("testuser:Hello World!"));
} catch (Exception e) {
e.printStackTrace();
}
} } Jetty package Cactus.test.support;
import org.mortbay.jetty.Connector; import org.mortbay.jetty.Server; import org.mortbay.jetty.bio.SocketConnector; import org.mortbay.jetty.servlet.ServletHandler; import com.meterware.httpunit.WebConversation; import com.meterware.httpunit.WebResponse; import junit.framework.Assert; import junit.framework.TestCase; public class JettySampleTest extends TestCase { Server server; protected void setUp() throws Exception { //通过代码设置并启动一个服务器,该服务器是servlet的测试容器 super.setUp(); server = new Server(); Connector connector=new SocketConnector(); connector.setPort(80); server.setConnectors(new Connector[]{connector}); ServletHandler handler=new ServletHandler(); server.setHandler(handler); handler.addServletWithMapping("Cactus.HelloWorld", "/"); server.start(); } protected void tearDown() throws Exception { super.tearDown(); server.stop(); } public void testHellWorld() { try { WebConversation wc = new WebConversation(); WebResponse web = wc.getResponse("http://127.0.0.1/HelloWorld"); String result=web.getText(); Assert.assertEquals(result,"null:Hello World!"); } catch (Exception e) { e.printStackTrace(); } } }
airlines 航空公司 XX is one of the most well-known airlines in the world.
square 广场 the are 4 statues,and fuontains,in the middle of Trafalgar square in Londen.
understand 理解 I wish he'd speak slower,I don't understand him.
参考:http://caterpillar.onlyfun.net/GossipCN/JUnit/JUnitGossip.htm 1. TestSuite public static Test suite() { TestSuite suite = new TestSuite(MathTool.class); suite.addTest(new MathToolTest("testGcd")); }
2.全局属性 protected void setUp() throws Exception { super.setUp(); arr = new ............; }
protected void tearDown() throws Exception { super.tearDown(); arr = null; }
3. Cactus web设置
http://caterpillar.onlyfun.net/GossipCN/JUnit/FirstCactusWithTomcat.htm http://caterpillar.onlyfun.net/GossipCN/JUnit/FirstCactusWithJetty.htm
我的编码标准。(随时间完善)
1. 建立工作区 -bin 编译地点,-lib 包,-javadoc doc, -src 源码区 |-设计功能包 |-interface 功能描述接口 |+com 功能实现包 |-test 测试区 |-support 功能可行分析 |-unit 单元测试 |-api 使用文档 |+设计代码区 |+设计功能包 |+设计功能包 ..... 初建立测试先行(迭带开发)。原则上不手动建立类、接口。可以先命名后通过eclipes工具建立。 (1)test.api 测试。也叫主功能测试。该测试主要目的是: 1>(接口级)功能描述,为再次使用提供帮助。 结合javadoc和代码本身描述 javadoc 使用 2>建立功能接口。 在次步骤是:先Ctrl+C命名,再shift+ctrl+N选择interface在package中去掉前面的test.api. (2)test.support 测试。也叫可行分析测试。该测试目的是(接口级)功能分为(方法级)功能并为各实现一个测试方法。 (3)test.unit 测试。也叫单元测试。该测试目的是: 1>方法级功能设计提升为类级、抽象类级(设计实现类)。 在次步骤是:先Ctrl+C命名,再shift+ctrl+N选择class在package中换test.unit.为com 2>方法依赖描述,为再次使用提供帮助。 (4)重构。 重构 eclips 快键建立中 1.接口级功能添加。和初建立相同。 2.抽象类、类级功能添加。从 test.support 测试开始。
开发包对应 test.api <-> interface test.support 无 test.unit <-> com
在写大量代码时发现没有个限定的标准是见可怕的事情。但我的动态面向对象数据库操作这个我自己的小东西时在编码很好用。不管是再次修改,直接copy到另个项目改改。都能很好的工作。而其他的小东西却不行。这仔细的总结下。
eclipse中如何写一个测试私有方法的junit? 假设类Summer定义如下:
public class Summer{ private int methodone( String argsone){ //method code ....... return 4; } } 测试如下: public class SummerTest extends TestCase { public void testMethodone(){ Object rightResult = xxxxx; Summer example = new Summer.newInstance(); Method m = example .getClass() .getDeclaredMethod(" methodone",new Class[]{ String.class}); m.setAccessible(true); Object result = m.invoke(example ,new Object[] {new String(xxxx)}); m.setAccessible(false); if (result.equals(rightResult)){ //your code ...... } } }
1.CollectionHelper 对List,Set,Map 包装出不可修改的 public final class CollectionHelper { public static final List EMPTY_LIST = Collections.unmodifiableList( new ArrayList(0) ); public static final Collection EMPTY_COLLECTION = Collections.unmodifiableCollection( new ArrayList(0) ); public static final Map EMPTY_MAP = Collections.unmodifiableMap( new HashMap(0) ); private CollectionHelper() {} }
1.1 在Collections.unmodifiableList(...)是静态内部类个构造方法 悟: 从上面看出是一个非常好的 适配器 //1.Collections 中 new 出内部类 public static <T> Collection<T> unmodifiableCollection(Collection<? extends T> c) { return new UnmodifiableCollection<T>(c); }
//2.内部类也继承 Collection static class UnmodifiableCollection<E> implements Collection<E>, Serializable { private static final long serialVersionUID = 1820017752578914078L;
final Collection<? extends E> c; //3.很好适配 Collection 通过他把 add remove 等功能 封装 UnmodifiableCollection(Collection<? extends E> c) { if (c==null) throw new NullPointerException(); this.c = c; } ...............
2.大量使用内部类枚矩 ?如: Mappings.PropertyReference upr = (Mappings.PropertyReference) iter.next(); //////////////////////////////////////////////// Mappings中 static final class PropertyReference implements Serializable { String referencedClass; String propertyName; boolean unique; }
//感觉是可以更好的代码编写
1. 接口里面的属性在默认状态下面都是public static
2. 被声明为final的变量必须在声明时给定初值,而在以后的引用中只能读取,不可修改。
3. 匿名的内部类是没有名字的内部类。不能extends(继承) 其它类,但一个内部类可以作为一个接口,由另一个内部类实现。
4. 静态内部类(Inner Class)写成这样才可以 在内部 new 出 : static final public class XXXxx 1.创建一个static内部类的对象,不需要一个外部类对象 2不能从一个static内部类的一个对象访问一个外部类对象
5.
HashMap 类没有分类或者排序。它允许一个 null 键和多个 null 值。 Hashtable 类似于 HashMap,但是不允许 null 键和 null 值。它也比 HashMap 慢,因为它是同步的。
6. GC
System.gc() Runtime.getRuntime().gc()
7.重写Overriding和重载Overloading 如果在子类中定义某方法与其父类有相同的名称和参数,我们说该方法被重写 (Overriding)。 如果在一个类中定义了多个同名的方法,它们或有不同的参数个数或有不同的参数类型,则称为方法的重载(Overloading)。Overloaded的方法是可以改变返回值的类型。
8.抽象类是否可继承实体类(concrete class) 抽象类是否可继承实体类,但前提是实体类必须有明确的构造函数
9.try {}里有一个return语句,那么紧跟在这个try后的finally {}里的code会不会被执行,什么时候被执行,在return前还是后? 会执行,在return前执行。
10.switch(expr1)中,expr1是一个整数表达式。因此传递给 switch 和 case 语句的参数应该是 int、 short、 char 或者 byte。long,string 都不能作用于swtich。
1。项目中 ->Exprot.. -> @javadoc 就可以了 2。javadoc 命令学习 @author 作者 @see 另请参见 (1)、@see "string" 为"string"添加文本项,不产生链接。 (2)、@see <a href="URL#Value">Label</a> 使用HTML标记产生链接 (3)、@see package.class#member Label 使用Java语言的名字package.class #member产生链接。
@version 版 @since 从以下版本开 @param 参数说明
/** */中的开头是注解
- /**
*/ 的就近原则 在那个上面就为那个注解
参照:http://java.ccidnet.com/art/3743/20031203/519697_1.html /** class description */
3、Variable Description:描述变量的意义和取值含义。 /** var variable description */
4、Method Description:标明每个方法的输入、输出参数和返回值类型,说明特殊变量取值的含义。相关类文档链接。
/** method description * @param var signification 方法参数说明 * @exception exception class name throws 说明 * @return return_value return signification return 说明 */
5、Association Description:关联类文档描述,在注释当中需要参引其它文档描述的地方,可在相应的注释当中如下插入: /** method description
* @param var signification * @exception exception class name * @return return_value return signification * @see package.class#member label */
6、包描述文件:概括描述包的功能和设计概要。为每个包创建一个描述文件,命名为package.html,与包的java文件放在一起。
-
如有错误大家多指教 1.call(* *(..)) 和 execution(* *(..)) 区别 call 和 execution 都为切面限定 execution 进行切面添加只能在方法定义的开始和结束。如: >>>AOP 添加 public String getName(){ System.out.println("G_G"); return this.name ; } >>>AOP 添加 call进行切面添加没有限定。如: >>>AOP 添加 public String getName(){ >>>AOP 添加 System.out.println("G_G"); >>>AOP 添加 return this.name ; } >>>AOP 添加
2.this 和within的区别
都为范围限定作用,如: within(Demo) && execution( * *(..)) 在类Demo中的所有.. 区别是:this不能切静态,within没有
3.cflow的作用 我们从 1>cflow( within(DD+) && execution( * *(..)) ) 和 2>within(DD+) && execution( * *(..)) 的区别来看 1与2的对比是在2的切入点下再加 aj 文件的方法 进行添加切入点。
4.方法添加 如:Introduction Example例中的 CloneablePoint.aj Point类继承Clonable 添加 clone() 方法 declare parents: Point implements Cloneable;
public Object Point.clone() throws CloneNotSupportedException { return super.clone(); }
point.clone()....
学习拥有连贯 在我刚认识 让 java 动态 这种动态编译动态加载的几天后 对我一向不懂的 AOP 特别是 AspectJ 开窍了 (哈哈 那感觉好啊^_^) 下面我写出我刚对AOP的一些小练 1。目的 DAO中大量的 session的开和闭 不紧使代码成倍加,还及容易出错 用 设计模式 hibernate 包装 下大家好象有点接受不了(@_@!) AOP就进入我的视线 但总没个切入点 2。原理
其实 让 java 动态 就是那点东西 但IBM 包出个好用的框架 来 。 3。代码说明
//*******************Dao.java **************************** package tt; //为了简单 session 看成是 真的session 哈 ^_^ public class Dao { public String session = "close" ; public void testDao(){ System.out.println( "testDao in function : "+ session); } static public void main(String[]args){ Dao dao = new Dao() ; dao.testDao(); System.out.println("main in function : " + dao.session); } }
//*****************List.aj **************************** package tt;
public aspect List { //切点 范围声明 (Dao.testDao 归 readOnly切点管 ) pointcut readOnly(Dao dao):execution(* *Dao.testDao*(..))&&this(dao);
//挂载 readOnly 开始方法 before(Dao dao) : readOnly(dao) { openSession(dao); } //挂载 readOnly 结束方法 after(Dao dao) returning() : readOnly(dao) { close(dao); } // readOnly 方法 运行代码 (到这可以大胆的写 java 代码了 ) 。。。。 private void openSession(Dao dao) { if(dao.session.equals("close")) dao.session = "Session Open"; } private void close(Dao dao) { dao.session = "close" ; } }
4。结果: testDao in function : Session Open main in function : close
4。后续 AspectJ 使 AOP 简单 可能还会统一标准 能为我们的java 框架灵活 更上一层 (期待)
下面 ( alt+shift+T ) 中都可以找到 1.改名 : ( alt+shift+R ) 2.类移动:( alt+shift+V ) 3.方法上移父类,下移子类 (alt+shift+T) + U/D 4.方法接口化 (alt+shift+T) +T 5.部分代码提升为方法 alt+shift+M 6.局部变量提升为类变量 alt+shift+F
.............
***************************************************************
Ctrl+M: 工作区最大化/最小化 Alt+/: 智能提示 F3: 察看声明 Crtl+1: 修正错误 Shift+Alt+T: 重构 Shift+Alt+M: 提取函数 Shift+Alt+R: 重命名 Shift+Alt+C: 更改函数标记 Ctrl+Shitf+F: 格式化代码
在WEB开发中 测试 在 C/S 而 实际运行 B/S 造成配置文件 在硬编码时总是改 。 但看 hibernate 的配置文件 确可以很好工作 ,没办法读源码 在框架中 发现 ConfigHelper类起到了作用 。 结合自己开发需求,写出了自己的 带查询文件功能类 扩展的主要部分在 findFile方法 这用了一下 简单的数据结构有兴趣的可以看看 测试: 文件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>
测试类
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") ); } }
结果: 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; }
}
为我准备学习和理解spring 特留下代码笔记: 参考:http://dev.csdn.net/author/labile/e70c97cb7f504d35b7b5350e7810cc5a.html代码感想: 没个方法都或多或少需要环境参数(如: jdbc的conn ,hbn的session...等等 ),方法结束后又要关闭。 何不用proxy代理并用配置文件的方法来 关,开session 等 如:以下是我的想法并不是实际可用 配置: <class name="HelloWorldImpl"> <function name="set*" />
<function name="getName"> <proxyBegin artt="name" value="liukaiyi"/> //使用Proxy来赋值 name那在实现代码中就可以不用去关注象 session 等属性的开关了 //proxy中配置下 , 在实现类中 就使用 就可以了 <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();
结果是: before method invoke! 刘凯毅 after method invoke!
在此 我只是想象,spring 还没有看,但我认为spring 这个著名的框架应该在这方面有很好的实现。
实际代码:希望spring可以向我上面的方法配置好用来取代下面的实际代码 ^_^
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 { //要代理的原始对象 private Object objOriginal; /** * 构造函数。 * @param obj 要代理的原始对象。 */ 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") ){ //方法调用之前 doBefore(); //仿佛是AOP的影子,呵呵 } //调用原始对象的方法 result = method.invoke(this.objOriginal ,args); //方法调用之后 doAfter(); return result ; } private void doBefore() { System.out.println("before method invoke!"); } private void doAfter() { System.out.println("after method invoke!"); } }
结果: Hello World! after method invoke!
before method invoke! 刘凯毅 after method invoke!
在 D2D 论坛中见 一文标题 《在java中利用动态编译实现eval》 http://dev2dev.bea.com.cn/bbsdoc/20060724298.html 虽然给出代码不能运行 但标题的意思已经达到 在此 我也不多说了 在此完善下原作者的代码 并使可运行来方便大家理解
企图说明: 代码的可用性是没有的,但代码向我们打开了一个使java动态编译的一向大门 有想法的程序员们。我们在此得到了什么?
代码说明: 1.为了使用例子的方便 testJavac.java 是 Bean ( name , avg ) 也是 逻辑类 ( eval(string) ) 2.运行请在 classpath 加入 java\lib\tools.jar jar 包 ( com.sun.tools.javac.Main ) 3.还是方便运行本例对 自己在什么 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(); //动态编译 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; } //调用Temp的rt方法返回结果: ClassLoader mc = this.getClass().getClassLoader(); Class clasz = mc.loadClass("Temp");
Method rt = clasz.getMethod("rt", new Class[]{}); return rt.invoke(clasz.newInstance(), new Object[] { }); //如果方法没有返回就直接调用 } public static void main(String[]args)throws Exception{ testJavac jj = new testJavac(); System.out.println( jj.eval(args[0]) ); }
} 运行结果 D:\javac>javac -classpath D:\java\lib\tools.jar;. testJavac.java
D:\javac>java -classpath D:\java\lib\tools.jar;. testJavac getName 刘凯毅 //此时在当前目录下你可以看到 多了一个 Temp.java 和 Temp.class 文件 //再使用 CalssLoader.loadClass方法动态加载到运行环境中来 //创建 动态 加载 动态 (java 动起来了) 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 多属性(并值有一定修改后)等复杂赋 值 用 一句 *逻辑string* 就可以了 多属性不同类型 赋值了说明:1.sbean : testData 类有4个属性 personid ; workno ; hname ; dob ; 2.gbean 类我这用的是数据库动态类 ,有兴趣的可以看看我的另一遍blog 动态面向对象数据库操作 数据库 表 z_jcyy_basepersonnel 多属性 但 personid,workno,hname 不可以为空 3.这里 get set 赋值 使用的工具 LGUtil测试:
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 {
//只有一条数据的 一对一 public void testONE_TO_ONE()throws Exception{
//得到修改的 数据'0301003300' dob 时间为当前 一条值 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 目的是 包, 把 数据'0301003300'的 personid,workno,hname,dob 值通过一定逻辑赋值 LGUtil lb = new LGUtil(); lb.setDataList(listD); //数据加入 : 就是 gbean lb.setMapping(LGUtil.ONE_TO_ONE); //定义是一对一 get -> set lb.setVbClass(testData.class); // sbean 类 lb.setAttrLg(Date.class," ./${.+} ","action:date($this,'yy-MM-dd')"); //把gbean数据为Date类型的付值给 sbean 的string类型 并以 'yy-MM-dd'时间字符格式 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 (呵哈 我的口号哦^_^) } }); testData oo = (testData)lb.getVBean().get(0) ; //sbean 的值输出 : System.out.println(oo.getPersonid()+":"+oo.getHname()+":"+oo.getWorkno()+":"+ oo.getDob() ); //测试结束 数据库 改回去 dob 为空 BeanUtils.setProperty( list.get(0) ,"dob",null); dyd.updateOrInsert(list.get(0)); } //多条数据的多对一 :就是 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%' "); // 得到多条数据
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 }
//多数据的一对一 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 数据改值 下面 展现需要 (有不同哦) 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)); } }
结果:
//方法 testONE_TO_ONE(): dob为'yy-MM-dd' 0301003300:heha:3300:07-09-29
//方法testMANY_TO_ONE() workno 全加 就是方法3 的workno全加 (大家可以看看哦) 174005.0 //方法testOne_to_one() 全付值 (简单展示 也可以对没个属性修改付 如:dob 方法一样) 0301003300:张金栋:3300:07-09-29 0301003301:谷嘉奇:3301:78-09-21 0301003302:闫国春:3302:78-12-24 0301003304:解国强: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:高国良: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:李结: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:李小发: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:马强:3393:75-10-03 0301003397:齐永强:3397:77-04-06
有兴趣的可以看看我花了3 天写的代码(重构过一次应该还是可以看看的 ) 下载:myGGUtil.rar包说明: 本次 代码在 myGGUtil.LGBeanUtil.LGUtil 下 (^_^)大家提点意见哦 ! 我希望这个好的想法 能成一个框架 哦~~~
BUG修订 09-21 15:44
时间类不能Update 问题 (如果在上面时间前下载那请从新下载)
在上一版本有大改动 自用小框架:DB工厂 1. 添加 jdbc 事物 2. 结构更合理 3. 速度加快
工具简单说明 脱离 DB 影射包 java 数据类 ,动态在内存中生成 动态数据类 ( 使用BeanUtils的DyanBean类 ) . 操作DB 面向对象操作(当然是动态^_^) 为了更实用 我用了张 50多属性的大表进行测试.阅读起来可能有点困难,希望大家海涵. version jdk 1.4
下载 DyanDBUtils.rar
包文件说明 : Config : JDBC 需要的 驱动 密码等 DBResources : 根据Config给出 Connection , PreparedStatement DynaClass : 根据元数据 和 table 给出 动态BasicDynaClass SQLSpelling : 给出 sql 语句和 sql语句中 ? 的值 ,格式为 List : lise.get(0)为sql语句 后其他为值 DyanDBUtils.java : 为本Util主要入口点 也是运行点
数据库表 z_jcyy_basepersonnel 有53个属性 (什么类型都有) 4 个不为空属性 personid , workno , depotid , hname
测试
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(); } }
测试测试结果 (注意: 开头的 李家佳 3719 和后面的 3719 没变 就是事物的结果)
李家佳
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") //事物运行良好 哦
李家佳 3719
总结 事物 解决了 还有多表问题 大家多给点鼓励哦 ^_^
BUG 修改 :
09-20 因为 Oracle 取元数据的字符串需要 大写 至修改并下载更新 测试使用表 ID SN STATIONNAME SPELL DEPOTID -------------- ---- -------------------- ---------- ------- ------------------ 08050000390689 3 永安 ya ....版本升级 09-21 DyanDBUtils 动态面向对象数据库 操作由于 hibernate 还要table影射成class 这好处和坏处只有我们程序员知道了 只要修改数据库就大量影射附加工作要做 ,有时影射还有BUG弄的我们@#$%!.....(哈hibernate我是小鸟^_^),我----不要----影射 , 没有他们数据库就又回到jdbc.本人比较喜欢偷懒 哈哈 自己来个小框架吧( 就300来行的代码有兴趣的看看哦 )!!! 用到技术 BeanUtil , JDBC元数据(在这我可是好好看了下JDBC,其实他是很强的东西,大家应该好好用用^_^) 下载 DBFactory.rarDBFactroy 数据是:+----+-------+-------------+------------+ | id | title | description | buydate | +----+-------+-------------+------------+ | 6 | tt | asdgwgw | 1990-12-02 | +----+-------+-------------+------------+先看看测试吧
public class testNotKonw extends TestCase {
protected void setUp() throws Exception { //运行 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 : 目的是测试前 删除全部数据 DBFactory.getTools().delete(it.next()); } } public void testInsert()throws Exception{ // insert 要先new出来个 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 了 (简单吧) 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); } } }
控制台输出 //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')
代码关键说明: 关键在BeanUtil 的 DnayBean中 我通过元数据 得到了 这个Bean 属性.属性类型,还有表信息放在 getClass();的字符串中 EG: table=...;key=..,..,..;columns=...,..,; 后在insert , delet , update就是(先delete后insert^_^) 中 解析得到 动态写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()){ //元数据中得到 类型做 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 ; }
小结: 当然表连和多表 查 是没问题的 但在多表 delete , update 就还没有完成 (蛮难的 5555 还有 没时间) 单表的 delete update ,select,insert 都完成了 我会努力的 大家要是认为还可以 帮忙顶贴 哦 我会都都完善哦
本人特留使用 ( ^_^ 写html 不多 呵呵 ) 本页问题说明: 在第一次加载这3个页面的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 使用同统一对象,语法 . 数据从 sever 到 v层 和 v层 到 sever 方便. 简单说就是 JBean 不做修改拿到V层 当 JSBean (javascript 类) 中用
1.url 乱码问题参照 Ajax uri 乱码问题总结(IE,FF) 2.使用jar是 jxpath ; json ......(与相关) jxpath 参照 jxpath 学习笔记 json 参照 使用json-lib
例题说明 数据 name,avg 在通过 ajax json 后 avg +1 再展现到页面 本页需要 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 把数据传给 server //数据来源 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 处理 数据后返回的 结果 // 年龄 +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对象一样 ^_^ document.getElementById('xx').value
=
jsobj.name
+
':'
+
jsobj.avg ; } } //数据来源
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 传入数据 String str = req.getParameter("jsonStr") ; //java 方 string -> javaBean JSONObject jso = JSONObject.fromString(str); //javaBean 使用jxpathcontxt解读更方便 ^_^ //其实jso中是以 map 形式存区的 有兴趣的可以自己动手写下哦 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(好象有点多嘴了 哈哈 方便下入门人了) <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>
IE的URI的提交是有压缩的(google好象有)所以utf-8对ie 不太好用我们为了方便ie统一gbk 1.Tomcat 的 server.xml 的 Connector 中加入 URIEncoding="GBK" 2. server 类中加入 rpo.setCharacterEncoding("GBK"); req.setCharacterEncoding("GBK"); rpo.setContentType("text/html; charset=GBK"); 3.jsp 页面加入 <%@ page pageEncoding="GBK"%> <%@ page contentType="text/html; charset=GBK" %> IE乱码问题解决.如果还没解决那就@#$%...... FF的uri 好象默认是UTF-8 所以用 GBK就不方便了 就同上面的 改 UTF-8 就可以了 FF 和 IE 一起方便使用的我还没找到 . 例代码 var url = "/json/json?jsonStr="+ (new fun()).toJSONString() ; //这 Ajax 就没有乱码了 request.open("GET", url, true); request.send(null);
页面 的 LayOut 用: LayoutContainer 这里有个问题 html -> html 的乱码问题不是很好解决(可能是dojo 0.9 bug??) 这 top , left .... 等可以用 .jsp来做 再用dojoLayout加入主页面 .html
<!
DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"
>
<
html
>
<
head
>
<
title
>
Layout Container Demo 1
</
title
>
<
style
type
="text/css"
>
@import "http://127.0.0.1:7000/dojoCharset/js/dojo/dijit/themes/tundra/tundra.css"; @import "http://127.0.0.1:7000/dojoCharset/js/dojo/dojo/dojo.css"
</
style
>
<
script
type
="text/javascript"
src
="http://127.0.0.1:7000/dojoCharset/js/dojo/dojo/dojo.js"
djConfig
="parseOnLoad: true"
></
script
>
<
script
type
="text/javascript"
>
dojo.require(
"
dijit.layout.ContentPane
"
); dojo.require(
"
dijit.layout.LayoutContainer
"
);
</
script
>
</
head
>
<
body
class
="tundra"
>
<
div
dojoType
="dijit.layout.LayoutContainer"
style
="width: 100%; height: 100%"
>
//这里 href 是关键到入 top.jsp 还没乱码问题
<
div
dojoType
="dijit.layout.ContentPane"
layoutAlign
="top"
style
="background-color:red"
href
="http://127.0.0.1:7000/dojoCharset/html/top.jsp"
>
</
div
>
<
div
dojoType
="dijit.layout.ContentPane"
layoutAlign
="left"
style
="background-color:lightblue;width: 120px;"
>
</
div
>
<
div
dojoType
="dijit.layout.ContentPane"
layoutAlign
="client"
style
="background-color:yellow"
>
</
div
>
</
div
>
</
body
></
html
>
或者用 一种比较复杂但灵活的方法 <html> <head> <title>Dojo: Hello World!</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!-- SECTION 1 --> <script type="text/javascript" src="http://127.0.0.1:7000/dojoCharset/js/dojo/dojo/dojo.js"></script> <!-- SECTION 2 --> <script type="text/javascript"> function helloPressed() { dojo.xhrGet({ url: 'http://127.0.0.1:7000/dojoCharset/dojo', handleAs: "text", encoding: "utf-8", timeout: 5000, // Time in milliseconds load: function(data, ioArgs) { window.alert(data); // Prints "peach" document.getElementById('div').innerHTML = data ; // div 添加 } }); } dojo.addOnLoad(helloPressed); </script> <div id='div' /> </html>
1.ArrayList <script type="text/javascript">
dojo.require("dojox.collections.ArrayList");
dojo.addOnLoad(function(){ var a = ['a1','a2']; var arr = new dojox.collections.ArrayList(a); arr.add('xx1'); arr.add('xx2'); arr.add('xx3'); //迭带 var it = arr.getIterator(); while(!it.atEnd()){ document.writeln( it.get()); } //数量 document.writeln(arr.count); //删除 arr.remove('xx1'); var arr_str = arr.toString() document.writeln( arr_str ); });
</script> 与java的collections 很相同方法就不一一介绍了 addRange --add 集合 clear , clone , contains , indexOf , insert , item -- get(i), removeAt(i), reverse ???, sort, toArray . return object[]
1.画图
<!
DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//ZH-CN" "http://www.w3.org/TR/html4/strict.dtd"
>
<
html
>
<
head
>
<
meta
http-equiv
="Content-Type"
content
="text/html"
/>
<
script
type
="text/javascript"
src
="http://127.0.0.1:8000/lib/dojo/dojo_0.9/dojo/dojo.js"
djConfig
="parseOnLoad: true"
></
script
>
<
style
type
="text/css"
>
@import "http://127.0.0.1:8000/lib/dojo/dojo_0.9/dojo/resources/dojo.css"; @import "http://127.0.0.1:8000/lib/dojo/dojo_0.9/dijit/tests/css/dijitTests.css";
</
style
>
<
script
type
="text/javascript"
>
dojo.require(
"
dojox.gfx
"
); dojo.addOnLoad(
function
(){ container
=
dojo.byId(
"
gfx_holder
"
);
var
surface
=
dojox.gfx.createSurface(container,
385
,
385
);
//
创建图范围
surface.createImage({width:
30
, height:
40
, src:
"
http://127.0.0.1:8000/images/tomcat.ico
"
});
//
create
surface.createCircle({cx:
100
, cy:
100
, r:
20
}) .setFill('blue'); surface.createLine({x1:
0
, y1:
350
, x2:
700
, y2:
250
}).setStroke(
"
green
"
); surface.createRect({x:
70
, y:
70
, width:
20
, height:
20
}).setFill(
"
red
"
);
var
hour_hand_points
=
[{x:
50
, y:
82
}, {x:
100
, y:
15
},{x:
200
, y:
20
}]; surface.createPolyline(hour_hand_points).setFill('aqua');
var
m
=
dojox.gfx.matrix;
var
initial_matrix
=
m.translate(
250
,
250
); g
=
surface.createGroup().setTransform(initial_matrix);
var
f, s
=
{color:
"
black
"
, width:
1
}; f
=
"
#ffffff
"
; s
=
{color:
"
#000000
"
, width:
0.172
}; g.createPath(
"
M-122.304 84.285C-122.304 2000.285 -122.203 86.179 -123.027 86.16C-123.851 700.141 -140.305 38.066 -160.833 40.309C-160.833 40.309 -143.05 32.956 -122.304 84.285z
"
).setFill(f).setStroke(s); //画画 不过天知道画的是什么 });
</
script
>
<
div
id
="gfx_holder"
style
="width: 385px; height: 385px;"
></
div
>
</
html
>
case dojox.gfx.defaultPath.type: return this.createPath(shape); case dojox.gfx.defaultRect.type: return this.createRect(shape); case dojox.gfx.defaultCircle.type: return this.createCircle(shape); case dojox.gfx.defaultEllipse.type: return this.createEllipse(shape); case dojox.gfx.defaultLine.type: return this.createLine(shape); case dojox.gfx.defaultPolyline.type: return this.createPolyline(shape); case dojox.gfx.defaultImage.type: return this.createImage(shape); case dojox.gfx.defaultText.type: return this.createText(shape); case dojox.gfx.defaultTextPath.type: return this.createTextPath(shape); 可以create的 方法 2.图象拖动事件 -----正方形--------
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//ZH-CN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html" /> <script type="text/javascript" src="http://127.0.0.1:8000/lib/dojo/dojo_0.9/dojo/dojo.js" djConfig="parseOnLoad: true"></script> <style type="text/css"> @import "http://127.0.0.1:8000/lib/dojo/dojo_0.9/dojo/resources/dojo.css"; @import "http://127.0.0.1:8000/lib/dojo/dojo_0.9/dijit/tests/css/dijitTests.css"; </style> <script type="text/javascript">
dojo.require("dojox.gfx");
var container = null; var container_position = null; var surface = null; var surface_size = null;
var gShapes = {} var gShapeCounter = 0;
function makeCircleGrid(aShape) { var id = "shape_" + (gShapeCounter++); aShape.getEventSource().setAttribute('shapeid', id); dojox.gfx._addClass(aShape.getEventSource(), "movable"); gShapes[id] = aShape; }
var current_shape = null; var current_shape_window = null; var last_position = null;
function getShape(event) { var id = event.target.getAttribute('shapeid'); var s = id ? gShapes[id] : null; return s; }
function handleMouseDown(event) { var shape = getShape(event); if (shape) { current_shape = shape; last_position = { x: event.clientX - container_position.x, y: event.clientY - container_position.y }; var params = shape.getShape(); //正方形的是 params [x ,y width,height] var center = dojox.gfx.matrix.multiplyPoint(shape.getTransform(), params.x, params.y); var dx = last_position.x - center.x; var dy = last_position.y - center.y;
current_shape_window = { x1: params.width + dx, y1: params.height + dy, x2: surface_size.width + dx, y2: surface_size.height + dy }; } dojo.stopEvent(event); }
function handleMouseMove(event) { if(!current_shape) return; var x = Math.min(Math.max(event.clientX - container_position.x, current_shape_window.x1), current_shape_window.x2); var y = Math.min(Math.max(event.clientY - container_position.y, current_shape_window.y1), current_shape_window.y2); current_shape.applyTransform({dx: x - last_position.x, dy: y - last_position.y}); last_position = {x: x, y: y}; dojo.stopEvent(event); }
function handleMouseUp(event) { current_shape = null; dojo.stopEvent(event); }
function initGfx() { container = dojo.byId("gfx_holder"); container_position = dojo.coords(container, true); surface = dojox.gfx.createSurface(container, 500, 500); surface_size = surface.getDimensions(); surface_size.width = parseInt(surface_size.width); surface_size.height = parseInt(surface_size.height);
var aShape = surface.createRect({x: 70, y: 70, width: 20, height: 20}).setFill("red");
makeCircleGrid(aShape);
dojo.connect(container, 'onmousedown', handleMouseDown); dojo.connect(container, 'onmousemove', handleMouseMove); dojo.connect(container, 'onmouseup', handleMouseUp); // cancel text selection and text dragging dojo.connect(container, "ondragstart", dojo, "stopEvent"); dojo.connect(container, "onselectstart", dojo, "stopEvent"); }
dojo.addOnLoad(initGfx);
</script>
<style type="text/css"> .movable { cursor: pointer; } </style>
</head> <body> <h1>dojox.gfx: 100 draggable circles</h1> <div id="gfx_holder" style="width: 500px; height: 500px;"></div> </body> </html>
--------圆是-----------
function handleMouseDown(event) { var shape = getShape(event); if (shape) { current_shape = shape; last_position = { x: event.clientX - container_position.x, y: event.clientY - container_position.y }; var params = shape.getShape(); // 形状的不同 就是 params 的取值不同 params [cx,xy,r] var center = dojox.gfx.matrix.multiplyPoint(shape.getTransform(), params.cx, params.cy); var dx = last_position.x - center.x; var dy = last_position.y - center.y; var r = params.r; current_shape_window = { x1: r + dx, y1: r + dy, x2: surface_size.width - r + dx, y2: surface_size.height - r + dy }; } dojo.stopEvent(event); } 其他不用再说了吧!!
dojo0.9 一个完整的开发javascript包非常值得去学习。 有用的地方就不用多说了..... 开始学习吧 !基础:1. dojo.declare javascript类方便使用(继承,创造等等) <1>简单创造,使用<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//ZH-CN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html" /> <script type="text/javascript" src="http://127.0.0.1:8000/lib/dojo/dojo_0.9/dojo/dojo.js" djConfig="parseOnLoad: true"></script> </head> <body> </body> </html> <script type="text/javascript"> dojo.declare("DojoClass",null,{ prptId: 'foo', method:function(val){ window.alert(val); } }); var obj = new DojoClass(); obj.method('XX'); //效果 alert('XX') </script> <2>简单继承
<script type="text/javascript"> dojo.declare("DojoClass",null,{ prptId: 'foo', method:function(val){ window.alert(val); } }); dojo.declare("Class",DojoClass,{ prptId2:'2222', method2:function(val){ window.alert("!!!"+val); } }); var obj = new Class(); obj.method('XX'); //效果 alert('XX'); obj.method2( obj.prptId+obj.prptId2 ); //效果 alert( '!!!foo2222' ); </script> <3>继承重写
<script type="text/javascript"> dojo.declare("DojoClass",null,{ prptId: 'foo', method:function(val){ window.alert(val); } }); dojo.declare("Class",DojoClass,{ prptId2:'2222', method:function(val){ val = val+'list'; this.inherited('method',arguments); }, method2:function(val){ window.alert("!!!"+val); } }); var obj = new Class(); obj.method('XX'); //效果 alert( 'XXlist' ); </script> <4> initializer 类构造 没成功 ?? 原因不明
<script type="text/javascript"> dojo.declare("DojoClass",null,{
initializer:function(val){ this.prptId=val; }, prptId: 'foo', method:function(val){ window.alert(val); } }); var obj = new DojoClass('liukaiyi'); obj.method( obj.prptId ); //效果 alert('foo'); 没成功 </script>
1。文件的映射。由于使用 MyEclipse(傻瓜版^_^) 所以 hibernate工具(extensions,Middlegen,tools等)一直没好好研究这就不献丑了。 2。Criteria 1)查询条件通过 Criteria.add 添加 Expression 用于描述条件 Expression.( and or like in le lt ..... ) 参见: Criteria查询 2)criteria.setFirstResult(100); criteria.setMaxResults(20); //检索范围 criteria.addOrder(Order.asc("name")); //排序 .add( Expression.sql("lower($alias.name) like lower(?)", "Fritz%", Hibernate.STRING) //直接嵌入SQL 3)Cat cat = new Cat(); .... List results = session.createCriteria(Cat.class).add( Example.create(cat) ).list(); //根据对象查询 3。HQL 完全面向对象的,具备继承、多态和关联等特性。 1)参见: HQL 2)内连接,inner join 左外连接,left outer join 右外连接,right outer join http://www.hibernate.org/hib_docs/reference/en/html/queryhql.html 代表性的语句 Hql.hbm.xml <set name="fkSet" inverse="true"> <key column="id"/> <one-to-many class="Fk"/> </set> SQL alter table fk add constraint FK_hf foreign key(id) references hql(id)
mysql> select * from hql;
+----+----------+
| id | name |
+----+----------+
| 0 | liukaiyi |
| 1 | heha |
+----+----------+
2 rows in set (0.00 sec)
mysql> select * from fk;
+----+------+
| id | name |
+----+------+
| 0 | yy |
| 1 | xx |
+----+------+
2 rows in set (0.00 sec)
//简单的 结果: 2 liukaiyi:heha
Query qu = se.createQuery("select h.name " + " from Hql h , Fk f" + " where h.id = f.id" ); List list = qu.list() ; tr.commit(); System.out.println( list.size() ); System.out.println( list.get(0)+":"+list.get(1) ); //给出对象 结果 : hehaQuery qu = se.createQuery("from Hql h where h.fkSet.name='xx'"); ((Hql)list.get(0)).getName() ;
//给出Object 结果:heha xxQuery qu = se.createQuery("select h.name,f.name from Hql h join h.fkSet f where f.name='xx'"); List list = qu.list() ; tr.commit(); System.out.println(list.size()); Object[] objs = (Object[]) list.get(0) ; System.out.println( objs[0] +":"+objs[1] );
//给出 Map heha xx
Query qu = se.createQuery("select new map( h.name as hn,f.name as fn)from Hql h join h.fkSet f where f.name='xx'"); List list = qu.list() ;
tr.commit(); System.out.println(list.size()); Map map = ((Map)list.get(0)); System.out.println( map.get("hn") ); } //报表语句 结果: 1 Query qu = se.createQuery("select count(*) from Hql h join h.fkSet f " + " where h.name='heha' and h.id=f.id " + " group by h.name "); List list = qu.list() ; tr.commit(); System.out.println( list.get(0) ); //集合内 结果 liukaiyi:heha //元素集(elements与indices 函数) 可以使用 any, some, all, exists, in //EG: from Player p where 3 > all elements(p.scores) +----+----------+ | id | name | +----+----------+ | 0 | liukaiyi | | 1 | heha | | 3 | oo | +----+----------+ Query qu = se.createQuery("select h.name " + " from Hql h" + " where h.id in elements(h.fkSet.id) " ); List list = qu.list() ; tr.commit(); System.out.println( list.get(0)+":"+list.get(1) ); //使用 javaBean 绑定
Query q = s.createQuery("from foo Foo as foo where foo.name=:name and foo.size=:size"); q.setProperties(fooBean); // fooBean包含方法getName()与getSize() List foos = q.list();
问题:
IE,FF用 xpath 在javascript动态解读 解决: 自定义jsXpath 类 js.js //关键是 jsXpath 类 //使用是 new 并 给属性 domx 值 DOMXml //var nodes = obj.getPathNodes( xpath ); 就是 xpath语句如://beans/bean //再 var node = obj.next( nodes ) //node 可以使用了
var dom = null ; var jp = new jsXpath();
function load(ul){ new Ajax.Request( ul, { method: 'get', onComplete: action }); }
function action(req){ var path = " /beans/bean[string-length(@xid)<3] "; dom = req.responseXML ; jp.domx = dom ; var list = jp.getPathNodes(path) ; createSelect(jp,list, document.getElementById('ii') ); //建 select ii }
function jsXpath(){ this.nexti = 0 ; this.domx = null ; this.getPathNodes = function(path){ var val =null ; if( navigator.appName.indexOf('Microsoft')== -1 ){ val = document.evaluate(path,this.domx ,null,XPathResult.ANY_TYPE,null ) ; }else{ this.domx.setProperty("SelectionLanguage","XPath"); val = this.domx.documentElement.selectNodes( path ) ; } return val ; } this.next = function(domp,ii){ if( navigator.appName.indexOf('Microsoft')== -1 ){ return domp.iterateNext() ; }else{ if(ii!=null) this.nexti = ii ; return domp[this.nexti++]; } } }
function createSelect(xpath,doms,sele){ try{ var item=xpath.next(doms); while(item){ var opt =document.createElement('option'); var text=document.createTextNode( item.firstChild.nodeValue ); opt.appendChild(text); opt.setAttribute("value",item.getAttribute('xid') ); sele.appendChild(opt); item = xpath.next(doms); } }catch(e){dump(e);} }
//建 select jj 与 select ii的 selectedIndex 有关 function duSel(){ var sele = document.getElementById('jj'); var sdom = document.getElementById('ii'); var num = sele.getElementsByTagName('option').length-1; for(var i=num; i>0 ; i--) sele.remove(1); var skey = sdom.options[ sdom.selectedIndex ].value
var path = "/beans/bean[ starts-with( @xid , '"+skey+"') and string-length(@xid)>3 ]";
var jpp = new jsXpath(); jpp.domx = dom ; var lj = jpp.getPathNodes(path);
createSelect(jpp,lj, document.getElementById('jj') ); }
xml.xml <?xml version="1.0" encoding="GB2312" standalone="no"?> <beans> <bean xid='01' >北京局</bean> <bean xid='0101'>ftd</bean> <bean xid='0102'>tsd</bean>
<bean xid='02'>沈阳局</bean> <bean xid='0202'>sy1</bean> <bean xid='0203'>sy2</bean> <bean xid='0204'>sy3</bean> </beans> xpath.html //级连的 下拉框出来了<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> <script language='JavaScript' src="js/js.js"></script> <script language="JavaScript" src="lib/prototype/prototype.js"></script> <script language='JavaScript' src='js/xpath.js'></script> </head>
<body onload='load( "./xml/xml.xml" )'> <select id="ii" onchange='duSel();'> <option value="" >--段选择--</option> </select> <select id="jj"> <option value="" >--车间选择--</option> </select> </body> </html>
心得: xpath 是好东西 好东西啊
问题:
java 可以用 xpath ; javascriopt 也可以! 解决: document.evaluate 方法 参考:浏览器中的XPath支持xpath.html <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> <script language='JavaScript' src="js/js.js"></script> <script language="JavaScript" src="lib/prototype/prototype.js"></script> </head> <body onload='load( "./xml/xml.xml" )'> </body> </html> // xpath.js 是一个扩展包在这里是可以统一 方法IE ,FF都可以使用 evaluate方法 // http://www.blogjava.net/Files/Good-Game/xpath.rar 下载 // 说明 http://dev.infoaccelerator.net/spryDocs/overview-summary.html
get set 参考 BeanUtil 包 和 Xpath http://commons.apache.org/ 的 jxpath User's Guide
类的加载 JXPathContext context = JXPathContext.newContext( obj ); //和 xpath 的 范围确定
一般取值 存值
String fName = (String)context.getValue("firstName"); //setValue //参考 http://www.blogjava.net/Good-Game/archive/2007/08/10/135739.html
一般的统计和使用 c 为 list [id,name,.....]
JXPathContext context = JXPathContext.newContext(c); System.out.println( context.getValue("count( .[name='oo' and id='1' ] )") ); //对象 name=oo 和 id=1的有多少个 System.out.println( context.getValue("sum( .[name='oo' and id='1' ]/id )") );//对象name=oo和id=1的所有id相加
得到集合
Iterator threeBooks = context.iterate("books[position() < 4]"); //xpath 的位置函数 position 其他函数参考 http://www.w3.org/TR/xpath //4 Core Function Library xpath 使用
public class Employee { private Map addressMap = new HashMap(); { addressMap.put("home", new Address()); addressMap.put("office", new Address()); } public Map getAddresses(){ return addressMap; } } String homeZipCode = (String)context. getValue("addresses[@name='home']/zipCode"); //使用的是 addressMap map 的 key = home 的Address类属性的 zipCode xml 在程序 与 xpath 的切入点
<?xml version="1.0" ?> <vendor> <location id="store101"> <address> <street>Orchard Road</street> </address> </location>
<location id="store102"> <address> <street>Tangerine Drive</street> </address> </location> </vendor>
class Company { private Container locations = null;
public Container getLocations(){ if (locations == null){ URL url = getClass().getResource("Vendor.xml"); locations = new XMLDocumentContainer(url); } return locations; } } context = JXPathContext.newContext(new Company()); String street = (String)context.getValue( "locations/vendor/location[@id = 'store102']//street"); // 类Container的 属性 locations 头 vendor(xml内) ..... 建立 Path工厂 就是 自定义字符串 得到 自定义类
public class AddressFactory extends AbstractFactory { public boolean createObject(JXPathContext context, Pointer pointer, Object parent, String name, int index){ if ((parent instanceof Employee) && name.equals("address"){ ((Employee)parent).setAddress(new Address()); return true; } return false; } }
JXPathContext context = JXPathContext.newContext(emp); context.setFactory(new AddressFactory()); context.createPath("address"); context.createPathAndSetValue("address/zipCode", "90190"); // emp 类就是 createObject方法中的 Object //运行解析到 address字符 就进入 if中
建立内参
JXPathContext context = JXPathContext.newContext(auth); context.getVariables().declareVariable("index", new Integer(2));
context.setValue("$index", new Integer(3)); Book secondBook = (Book)context.getValue("books[$index]"); // $index 为 3
确定范围 Pointer JXPathContext context = JXPathContext.newContext(bean); Pointer addressPtr = context.getPointer("/employees[1]/addresses[2]"); JXPathContext relativeContext = context.getRelativeContext(addressPtr); String zipCode = (String)relativeContext.getValue("zipCode"); //可以用 xpath 确定范围 很好 呵呵
方法的联系应用
public class Formats { public static String date(Date d, String pattern){ return new SimpleDateFormat(pattern).format(d); } } context.setFunctions(new ClassFunctions(Formats.class, "format")); //方法的设置 format context.getVariables().declareVariable("today", new Date()); String today = (String)context.getValue("format:date($today, 'MM/dd/yyyy')");
心得: 代码可以写成什么样呢~~ (JXpath)
参考: http://www.duduwolf.com/wiki/2007/296.html http://www.chinaitpower.com/A/2005-07-03/150232.html1)普通的Bean处理 不管是什么Set参数为3个 ( 对象本身, 属性名或属性内位置, 值 ) //list的add有点特别 Get参数为2个 ( 对象本身, 属性名或属性内位置 ) Employee em = new Employee(); //String name; String[] ss; Map map; List list; BeanUtils.setProperty(em,"name","liukaiyi"); //String set BeanUtils.setProperty(em,"ss",new String[]{"1","2","3"}); //String[] set BeanUtils.setProperty(em,"ss[2]","google"); //String[2] set
BeanUtils.setProperty(em,"map",new HashMap()); //Map set BeanUtils.setProperty(em,"map(key)","value"); //Map.put(Key,Value) BeanUtils.setProperty(em,"list",new ArrayList( Arrays.asList( new Object[20] ) )); //List有点特别 BeanUtils.setProperty(em,"list[0]","list"); //不可以直接添加??? BeanUtils.setProperty(em,"avg","23"); //int set System.out.println( BeanUtils.getSimpleProperty(em,"name") ); System.out.println( BeanUtils.getProperty(em,"ss[2]") ); System.out.println( BeanUtils.getProperty(em,"map(key)") ); System.out.println( BeanUtils.getProperty(em,"list[0].class") ); // 取的是 ==list.get(0).getClass() System.out.println( BeanUtils.getProperty(em,"avg") );
2)动态属性 //定义动态属性集 DynaProperty[] props = new DynaProperty[]{ new DynaProperty("address", java.util.Map.class), new DynaProperty("subordinate", mypackage.Employee[].class), new DynaProperty("firstName", String.class), new DynaProperty("lastName", String.class) }; //创建动态类来设定动态属性值 BasicDynaClass dynaClass = new BasicDynaClass("employee", null, props); DynaBean employee = dynaClass.newInstance(); employee.set("address", new HashMap()); employee.set("subordinate", new mypackage.Employee[0]); employee.set("firstName", "Fred"); employee.set("lastName", "Flintstone");
//也可以同上一样 提供统一 的Get Set 还是 字符操作 ^o^ 哈哈 BeanUtils.setProperty(bean,"address",new HashMap()); BeanUtils.setProperty(bean,"address(ads1)","江西"); BeanUtils.setProperty(bean,"name","liu"); BeanUtils.setProperty(bean,"subordinate",new String[3]); BeanUtils.setProperty(bean,"subordinate[1]","heha"); System.out.println( BeanUtils.getProperty(bean,"address(ads1)") ); System.out.println( BeanUtils.getProperty(bean,"name") ); System.out.println( BeanUtils.getProperty(bean,"subordinate[1]") );
3)JDBC 扩展 Connection conn = ; Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery ("select accountid, name from customers"); Iterator rows = (new ResultSetDynaClass(rs)).iterator(); //ResultSetDynaClass(java.sql.ResultSet resultSet) while (rows.hasNext()) { //利用动态bean进行输出 DynaBean row = (DynaBean) rows.next(); //连实体Bean都可以不要了 BeanUtils.copyProperties( MyBean ,row ); // bean<--dynaBean 就这样去得到值 ^o^ MyBean.getAccountid(); .... } rs.close(); stmt.close(); 4)HttpServletRequest 扩展 HttpServletRequest request = ; MyBean bean = ; HashMap map = new HashMap(); Enumeration names = request.getParameterNames(); while (names.hasMoreElements()) { String name = (String) names.nextElement(); map.put(name, request.getParameterValues(name)); } BeanUtils.populate(bean, map);//bean<--map struts好象是就用这个 Form
问题:
当IE 禁用javascript 怎么验证数据 解决:Struts validation 框架 1)先 建 Form类 extendsValidatorForm private String name ; private String pass ;
2) Jsp 建立
<body> <font color="red" ><html:errors/></font> <html:form action="/test"> name:<html:text property="name" /> pass:<html:text property="pass" /> <html:submit>submit</html:submit> </html:form> </body> 3)validator.xml建立
<?xml version='1.0'?> <!DOCTYPE form-validation PUBLIC "-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.0//EN" "http://jakarta.apache.org/commons/dtds/validator_1_0.dtd"> <form-validation> <formset> <form name="testForm"> <field property="name" depends="minlength,maxlength,mask"> <msg name="minlength" key="err.minlength" /> <!-- 当 minlength错时 msg 激活 --> <msg name="maxlength" key="err.maxlength" /> <arg0 key="${var:maxlength}" resource="false"/> <arg1 key="${var:minlength}" resource="false"/> <var> <var-name>maxlength</var-name> <var-value>5</var-value> </var> <var> <var-name>minlength</var-name> <var-value>3</var-value> </var> </field> </form> </formset> </form-validation> 4)ApplicationResources.properties
# Resources for parameter 'com.validator.struts.ApplicationResources' # Project P/validator err.minlength= err min < 3 err.maxlength= err max > 5 心得: validation 这是个难啃的骨头 要多多的接触
java package test;
import java.io.StringWriter;
import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathExpression; import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document; import org.w3c.dom.Element;
import com.opensymphony.xwork2.ActionSupport;
public class TAction extends ActionSupport { private String xml1; public String getXml1() { return xml1; } public void setXml1(String xml1) { this.xml1 = xml1; } { try { DocumentBuilderFactory factory = DocumentBuilderFactory .newInstance(); DocumentBuilder builder = factory.newDocumentBuilder();
// 创建 Document document = builder.newDocument(); Element root = document.createElement("root"); document.appendChild(root); Element name = document.createElement("name"); name.setAttribute("type", "ok"); name.appendChild(document.createTextNode("liu!k>a^i!@$^*><{}yi")); root.appendChild(name);
// 从数据库提取 // String xmlstr= "<beans><name>liu</name><pass>123</pass></beans>"; // builder.parse(new ByteArrayInputStream(str.getBytes()));
// save to mysql StringWriter output = new StringWriter(); TransformerFactory.newInstance().newTransformer().transform( new DOMSource(document), new StreamResult(output)); //System.out.println(output.toString());
// 对内展现 XPathFactory factoryXpah = XPathFactory.newInstance(); XPath xpath = factoryXpah.newXPath(); XPathExpression expr = xpath.compile("//name"); System.out.println(expr.evaluate(document)); expr = xpath.compile("//name/@type"); //System.out.println(expr.evaluate(document));
// 对jsp jstl xml // 参考 http://www.java2s.com/Code/Java/JSP/XML.htm
this.xml1 = output.toString().replaceAll("<\\?.*\\?>", ""); } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { System.out.println(new TAction().getXml1()); }
}
jsp <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@taglib uri="http://java.sun.com/jstl/xml_rt" prefix="x"%> <%@taglib uri="http://java.sun.com/jstl/core_rt" prefix="c"%> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> </head> <body> <c:import url="http://127.0.0.1:38080/ljw_svn2/test/data.do" var="webXml" /> <x:parse xml="${webXml}" var="doc" /> <x:out select="$doc//name"/><br /> </body> </html> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@taglib uri="http://java.sun.com/jstl/xml_rt" prefix="x"%> <%@taglib uri="http://java.sun.com/jstl/core_rt" prefix="c"%> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> </head> <body>
<c:set var="basepath" value="<%=request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/" %>"></c:set> <c:import url="${basepath}/infoPublishing.do?c=showXmlData&bid=63" var="webXml" /> <x:parse xml="${webXml}" var="doc" /> 类型:<x:out select="$doc//typeFlag"/><br /> qq:<x:out select="$doc//qq"/><br /> msn:<x:out select="$doc//msn"/><br />
</body> </html>
问题:
jsp 的简化与 统一性 解决: EL 标签 jsp.页面 <%@ taglib prefix="fn" uri="/WEB-INF/fn.tld" %> <%@ taglib prefix="c" uri="/WEB-INF/c-1_0-rt.tld" %> <%@ taglib prefix="x" uri="/WEB-INF/x-1_0-rt.tld" %> <%@ page isELIgnored="false" %> <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<% 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 'MyJsp.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"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <c:set var="url"><%=basePath%>/xml</c:set> <c:import var="xmlDoc" url="${url}"/> <x:parse xml="${xmlDoc}" var="doc" />
//xml解析 <c:set var="bookName" ><x:out select="$doc/xml-body/books/book[@id='1']"/></c:set>
//xml 定位 ${fn:substring(bookName,"0", fn:length(bookName)-2 ) }<br> //字符substring
<x:forEach var="item" select="$doc/xml-body/books/book" > //迭带 <x:out select="$item" /><br> </x:forEach> </body> </html>
结果得到是: book1_goog book1_google book2_baidu book3_tiancai/xml 路径是 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;
public class XmlServlet extends HttpServlet { /** * */ private static final String CONTENT_TYPE = "text/html; charset=GBK"; public void init() throws ServletException{} public void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException,IOException{ PrintWriter out = response.getWriter(); response.setContentType(CONTENT_TYPE); response.setCharacterEncoding("GBK"); out.print("<?xml version='1.0' encoding='UTF-8'?>"); out.print("<xml-body>"); out.print("<name>RW</name>"); out.print("<passWord>123456</passWord>"); out.print("<age>28</age>"); out.print("<books>"); out.print("<book id='1'>book1_google</book>"); //jsp 定位得到的 字符 out.print("<book id='2'>book2_baidu</book>"); out.print("<book id='3'>book3_tiancai</book>"); out.print("</books>"); out.print("</xml-body>"); } public void doPost( HttpServletRequest request, HttpServletResponse response ) throws ServletException,IOException{ doGet(request,response); } }
心得:写EL心情 就是好
JSP 自定义标签 1. <my:list pass="${pass}"/>pass 的建立是(1)tld文件加 <attribute>(2).java加 private String pass gget() gset() 2. 要有 Body .java 就继承 BodyTagSupport 不要就 TagSupport 3. doStartTag() 中 输出是 pageContext.getOut().print("hello."+this.pass); 4. doAfterBody() 中 输出是 BodyContent bc = super.getBodyContent(); String bStr = bc.getString(); // body 中的 string bc.getEnclosingWriter().print(...); // out to jsp 5. <my:list pass="liukaiyi"> <c:if test="${gg==null}"> //会先运行得到 String 再在 bc.getString()得到 String XX </c:if> </my:list> 4. .java 中 通过是 doStartTag() return SKIP_BODY 跳向 doEndTag() return EVAL_BODY_INCLUDE 跳过主体 doBodyContent() return EVAL_BODY_BUFFERED 调用doInitBody() 5. .java 中 doAfterBody() return SKIP_BODY 跳出循环 到 doEndTag() return EVAL_BODY_AGAIN 再次 doAfterBody() 6. .java 中 doEndTag() retrun EVAL_PAGE 继续剩余 return SKIP_PAGE 跳出
Tag 自定义标签 1. <%@ taglib prefix="my" tagdir="/WEB-INF/tags" %> 倒入 并在 tags 文件中 建 XXX.tag 2. 使用 EG: <my:文件名 /> 3. <my:MyTag items="${name}" />在文件.tag中加入 <%@ attribute name="items"%> 并在 body中${items}就可以使用 4. body加标签 同 JSP 自定义标签 5 5. <my:MyTag items="d" > <jsp:attribute name="list"> //添加body模块 ..<>.. </jsp:attribute> </my:MyTag> 在 .tag 中 <%@ attribute name="list" fragment="true" required="true" %> 取得 <jsp:invoke fragment="list" /> 使用中的 String
我开个头 希望大家 也贡献些 :-)
摘要: 问题:
用户在 WEB 中输入 机车 人员 等项 页面会根据当前字符给出选择提示解决:scriptaculous javascript工具包的 Autocompleter.Local 与图对应代码:Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->... 阅读全文
问题:
画页面 或 报表 的 图象问题 解决:用 通过xml画图 画笔wz_jsgraphics.js xml数据取得 prototype.js 画动作 Xmlgraphics.js (自己包装) 下载: http://www.blogjava.net/Files/Good-Game/Mywz_jsgraphics.rar 请放在 服务器上(tomcat) 并改 testLine.html页面上的 load( ul ) =>> ul ( xml 的取得地方 ) 请注意 : IE 5 支持不好 请用 火狐 或 IE6 图片 :
EG: 这展现了 画线 画图 到 画字的简单过程 <grabhics>
<line x1='0' y1='0' x2='40' y2='0' color='green' stroke='4' /> <line id='l1' x1='0' y1='0' x2='0' y2='200' color='darkblue' stroke='8' /> <rect x='20' y='20' w='40' h='70' color='hotpink' stroke='4' /> <rect id='r1' x='100' y='60' w='20' h='200' color='greenyellow' stroke='8' /> <fillRect x='50' y='60' w='40' h='70' color='darkolivegreen' stroke='2' /> <fillRect id='fr1' x='150' y='250' w='20' h='45' color='darkturquoise' stroke='1' /> <ellipse x='0' y='100' w='50' h='100' color='darkolivegreen' stroke='5' /> <ellipse id='e1' x='250' y='0' w='34' h='46' color='darkturquoise' stroke='7' /> <fillEllipse x='0' y='150' w='150' h='70' color='darkolivegreen' stroke='5' /> <fillEllipse id='fe1' x='250' y='20' w='84' h='48' color='gray' stroke='7' /> <fillArc x='32' y='124' w='130' h='170' start='0' end='190' color='red' /> <fillArc id='fa1' x='200' y='300' w='40' h='20' start='0' end='300' color='red' />
<polygon xs='32,80,23,7,64' ys='124,2,42,24,6' color='darkolivegreen' /> <polygon id='pp1' xs='32,4,2' ys='124,3,51' color='darkolivegreen' />
<fillPolygon xs='10,85,93,60' ys='50,10,105,87' color='00aaaa' /> <fillPolygon id='adfh' xs='80,126,-30,-60' ys='0,130,40,100' color='00aaaa' />
<image x='200' y='300' w='50' h='50' url='../image/test.bmp' /> <image id='ima' x='300' y='300' w='50' h='50' url='../image/test.bmp' />
<string font='arial' size='15' style='Font.ITALIC_BOLD' str='刘凯毅' x='300' y='400' color='red' /> <string id='strr' font='arial' size='20' style='Font.ITALIC_BOLD' str='万岁' x='310' y='420' />
</grabhics>
简单页面 : 给出 div 的 id (位置 和 xml 的出处 就可以了)load() 方法 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//ZH-CN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <script language="JavaScript" src='../lib/prototype/wz_jsgraphics.js' ></script> <script language="JavaScript" src="../lib/prototype/prototype.js"></script> <script language="JavaScript" src="../js/test.js" ></script> <script language="JavaScript" src="../js/Xmlgraphics.js" ></script> </head> <body onload='load( "http://127.0.0.1:8000/Mywz_jsgraphics/xml/graphics.xml" )'> <div id="myCanvas" style="position:relative;height:250px;width:100%;"> <input type='button' onclick='tt()' /> </div> </body> </html>
<script> function tt(){ var uu = 'strr' var g2 = getGdom(uu) ; getValue(uu).clear(); } </script>
1. 开始 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>TEST</title> <script type="text/javascript" src="wz_jsgraphics.js"></script> </head> <body> <div id="myCanvas" style="position:relative;height:250px;width:100%;"></div> </body> </html>
<script type="text/javascript"> <!--
var jg = new jsGraphics("myCanvas");
jg.setColor("#00aaaa"); jg.fillArc(100,200,200,150,0,20);
jg.paint();
//--> </script>
07-11-9 由于我对hibernate理解的深入,在次我来终结下这篇文章的不足的地方(好多人在拍砖哈) 对复杂的逻辑这样开和关太冒失了。 在普通的逻辑方法中 session都叠加的用上2次以上 这就要对一级缓冲的管理。事物的使用也是一样。
下载: http://www.blogjava.net/Files/Good-Game/hibernateUtil.rar简单的继承包 : 继承 DBManage 类 把 数据包装类 管理 ( 填充 , set 等 ) 后就直接放到里 insert , update , delete 方法中 填充可看看这个,很有实用价值 ----> ( 当 Form -> Bean 或 Bean ->Bean ) 例子很简单但想法表明 继承 DBSelect 类 为 select 这只是 把 Query 给出 简单用法 是 Query qu = dao.getQueryBegin( " HQL " ); qu.add ..... List li = dao.getQuertyEnd( qu ); 扩展: Criteria cr , SQLQuery , 等等 把她包装成 各个 dao 中 不是 很 偷懒 : ) Eg : extendsDBBasic 类 public List select(String id,String time){
List list = new ArrayList(); Query qu = getQueryBegin("HSQL"); //继承带来的好处 .add.......... List list = getQuertyEnd(qu); //继承结束 return list; } 缺点: 最好不要static 在一时间点上 此类不能支持多线程 basicBegin basicEnd 方法 ( 我找不到好的方法 要的话来个 连接池什么的 大家讨论西西吧!! ) sess 为全局的 session 要是 写成 baseicBegin 返回的话 感觉下面的还有很多要写 什么 close 啊... sess 也是缺点的所在 当然大家 有什么想法 改下 或自己来个 小包装 我只是 抛砖引玉 private Map transmap = new HashMap();
protected Session basicBegin(){ Session sess = SessionManager.currentSession(); try { transmap.put( sess, sess.beginTransaction() ); }catch(Exception e){System.out.println(e);} return sess ; } protected void basicEnd(Session sess){ try { ((Transaction)transmap.remove(sess)).commit(); }catch(Exception e){System.out.println(e);} finally{ sess = null ; SessionManager.closeSession(); } } 心得: 多包装多快乐
摘要: Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->
1 <rows><row id='1703' name='武昌南机务段 ' /><row id='1701' name='襄樊北机务段 ' />... 阅读全文
问题 :
提供给B/S 结构一个实时的运行展现 解决: prototype 的 Ajax.PeriodicalUpdater 更新 prototype 的 Ajax.Request 语句提交 action 语句的组织展现 http://www.blogjava.net/Files/Good-Game/take.rar 没有lib 大家可以就加 struct 相关 lib 就可以了 说明: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <SCRIPT language="Javascript" src="prototype1.5.0.js"></SCRIPT> </head> <body onload="Said()"> <INPUT id='name1' type="text" size="10" value="请输入名字" onfocus="if($('name1').value=='请输入名字') $('name1').innerText='' " /> <INPUT id='text1' type="text" onkeydown="if(event.keyCode==13){event.keyCode=0; onb();}"/> <INPUT id='button1' type="button" value="test" onclick='onb()' /> </body> <div id='div1'/> </html> <script type="text/javascript" > //语句异步提交给服务器 Ajax.Request function onb(){ if($('name1').value=='请输入名字' || $('name1').value==''){ window.alert('请输入名字'); return } var url = 'http://192.168.1.130:7000/xxs/mySaid.do?name='+$F('name1')+'&take='+$F('text1'); new Ajax.Request( url, { method: 'get', onComplete: action }); $('name1').readOnly = true $('name1').style.background = 'lightblue' $('text1').innerText='' } //局部刷新 并提取 语句 function Said(){ var url = 'http://192.168.1.130:7000/xxs/mySaid.do'; new Ajax.PeriodicalUpdater( 'div1', url, { method: 'get', onComplete: SumSaid, evalScripts: true, frequency: 1, decay: 1 } ); } //展现 function SumSaid(req){ $('div1').innerHTML = req.responseText; }
function action(req){ } </script> Action private static int SIZE = 30 ; private List list = new ArrayList();
public ActionForward execute( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { String take = request.getParameter("take") ; String name = request.getParameter("name") ; response.addHeader("Cache-Control","no-cache"); request.setAttribute("said",DueiLie(name,take));
try { request.setCharacterEncoding("gb2312"); response.setCharacterEncoding("gb2312"); } catch (Exception e) { }
return mapping.findForward("list"); } //语句的组织 public String DueiLie(String name,String take){ StringBuffer strb = new StringBuffer(); if(name==null||take==null); else{ strb.append( name ).append(" : ").append(take).append("</br>") ; if(list.size()==SIZE){ list.remove(list.get(0)); list.add(strb.toString() ); }else{ list.add( strb.toString() ); } } StringBuffer takes = new StringBuffer(); Iterator it = list.iterator(); while(it.hasNext()){ takes.insert( 0,(String)it.next() ); } return takes.toString(); } jsp ( list ) 中文处理 jsp 就一句话 <%= new String(((String)request.getAttribute("said")).getBytes("iso8859-1"),"GBK") %> 心得:别人做到了 我也能做到 要学的东西很多 多看书 多留意 多保护好身体
|