|
2007年10月18日
学习就从官方的测试开始,但不知道怎么回事官方的测试有问题,这我就把我配置的简单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()....
|