Ajax几个简单的案例(ajax_用户唯一验证、ajax_返回xml数据的处理(包括分页处理)
当然开发的前提是把相应的包导入项目中(开发环境myeclipse)
ajax_用户唯一验证(servlet):
如图在myeclipse中的ajax_servlet项目中的index.jsp实现页面的显示:
Index.jsp代码:
<%@pagelanguage="java"import="java.util.*"pageEncoding="UTF-8"%>
<%
Stringpath=request.getContextPath();
StringbasePath=request.getScheme()+"://"
+request.getServerName()+":"+request.getServerPort()
+path+"/";
%>
@H_404_108@<!DOCTYPE@H_404_108@HTMLPUBLIC@H_404_108@"-//W3C//DTDHTML4.01Transitional//EN">
@H_404_108@<basehref="<%=basePath%>"@H_404_108@>
@H_404_108@<title@H_404_108@>MyJSP'index.jsp'startingpage@H_404_108@</title@H_404_108@>
@H_404_108@<Metahttp-equiv="pragma"content="no-cache"@H_404_108@>
@H_404_108@<Metahttp-equiv="cache-control"content="no-cache"@H_404_108@>
@H_404_108@<Metahttp-equiv="expires"content="0"@H_404_108@>
@H_404_108@<Metahttp-equiv="keywords"content="keyword1,keyword2,keyword3"@H_404_108@>
@H_404_108@<Metahttp-equiv="description"content="Thisismypage"@H_404_108@>
<!--
<linkrel="stylesheet"type="text/css"href="styles.css">
-->
@H_404_108@<scripttype="text/javascript"
src="${pageContext.request.contextPath}/js/util.js"@H_404_108@></script@H_404_108@>
@H_404_108@<scripttype="text/javascript"
src="${pageContext.request.contextPath}/js/user/reg.js"@H_404_108@></script@H_404_108@>
@H_404_108@<divalign="center"@H_404_108@>
@H_404_108@<formaction=""@H_404_108@>
用户名:@H_404_108@<inputtype="text"id="uname"@H_404_108@/><spanid="cname"@H_404_108@></span@H_404_108@><br@H_404_108@>
密码:@H_404_108@<inputtype="password"id="upass"@H_404_108@/><br@H_404_108@>@H_404_108@<input
type="submit"value="注册"@H_404_108@/>
然后在webroot下新建一个js文件夹,这个里面写我们的js代码实现ajax使用
在util.js中封装了发送和接收的请求和一些必要的代码
//通过id获取dom对象
function$(id){
returndocument.getElementById(id);
}
//创建XMLHttpRequest对象
functioncreateXHR(){
//声明
varxhr;
//IE浏览器XMLHTTP组件的名称
varaVertion=["MSXML2.XMLHttp.5.0","MSXML2.XMLHttp.4.0","MSXML2.XMLHttp.3.0","MSXML2.XMLHttp.2.0","Microsoft.XMLHttp"];
try{
//firefoxopera等浏览器
xhr=newXMLHttpRequest();
}catch(ex){
for(vari=0;i<aVertion.lengrh;i++){
try{
xmlHttpRequest=newActiveXObject(aVersion[i]);
returnxmlHttpRequest;
}catch(ex){
continue;
}
}
}
returnxhr;
}
varxhr=createXHR();
functionsendPost(content,url,success,fail){
//ajax处理操作
//创建xhr对象
//触发器
xhr.onreadystatechange=function(){
if(xhr.readyState==4){
if(xhr.status==200||xhr.status==304){
success(xhr);
}else{
fail(xhr);
}
}
};
//打开请求
xhr.open("POST",true);
//设置类型
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
//发送请求
xhr.send(content);
}
然后再user下的reg.js中写要完成的代码
window.onload=function(){
//获取id="uname"节点对象
varunameDom=$("uname");
//为节点注册onblur事件
unameDom.onblur=function(){
varcontent="name="+unameDom.value;
//封装请求的url路径
varurl="./servlet/regUser.do?time="+newDate().getTime();
sendPost(content,disposeSuccess,disposeFail);
functiondisposeSuccess(){
$("cname").innerHTML=xhr.responseText;
}
functiondisposeFail(){
alert("请求失败");
}
};
};
最后在src下建立action处理方法
packagewww.csdn.net.servlet;
importjava.io.IOException;
importjava.io.PrintWriter;
importjavax.servlet.ServletException;
importjavax.servlet.http.HttpServlet;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
publicclassUserServletextendsHttpServlet{
/**
*
*/
privatestaticfinallongserialVersionUID=1L;
publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)
throwsServletException,IOException{
this.doPost(request,response);
}
publicvoiddoPost(HttpServletRequestrequest,IOException{
Stringname=request.getParameter("name");
System.out.println("===="+name);
response.setContentType("text/html;charset=utf-8");
PrintWriterout=response.getWriter();
if("xiao".equals(name)){
}else{
out.print("用户名可以使用");
}
out.flush();
out.close();
}
/**
*Initializationoftheservlet.<br>
*
*@throwsServletExceptionifanerroroccurs
*/
publicvoidinit()throwsServletException{
//Putyourcodehere
}
}
这样就完成了,发布到tomcat服务器上然后用火狐浏览器测试就可以了
ajax_用户唯一验证(struts2)
如图所示;
<%@pagelanguage="java"import="java.util.*"pageEncoding="UTF-8"%>
<%@tagliburi="/struts-tags"prefix="s"%>
<%
Stringpath=request.getContextPath();
StringbasePath=request.getScheme()+"://"
+request.getServerName()+":"+request.getServerPort()
+path+"/";
%>
@H_404_108@<!DOCTYPE@H_404_108@HTMLPUBLIC@H_404_108@"-//W3C//DTDHTML4.01Transitional//EN">
@H_404_108@<basehref="<%=basePath%>"@H_404_108@>
@H_404_108@<title@H_404_108@>MyJSP'index.jsp'startingpage@H_404_108@</title@H_404_108@>
@H_404_108@<Metahttp-equiv="pragma"content="no-cache"@H_404_108@>
@H_404_108@<Metahttp-equiv="cache-control"content="no-cache"@H_404_108@>
@H_404_108@<Metahttp-equiv="expires"content="0"@H_404_108@>
@H_404_108@<Metahttp-equiv="keywords"content="keyword1,keyword3"@H_404_108@>
@H_404_108@<Metahttp-equiv="description"content="Thisismypage"@H_404_108@>
<!--
<linkrel="stylesheet"type="text/css"href="styles.css">
-->
@H_404_108@<scripttype="text/javascript"
src="${pageContext.request.contextPath}/js/util.js"@H_404_108@></script@H_404_108@>
@H_404_108@<scripttype="text/javascript"
src="${pageContext.request.contextPath}/js/user/reg.js"@H_404_108@></script@H_404_108@>
@H_404_108@<divalign="center"@H_404_108@>
@H_404_108@<h3@H_404_108@>注册页面@H_404_108@</h3@H_404_108@>
@H_404_108@<divalign="center"@H_404_108@>
@H_404_108@<s:formaction="regUser"namespace="/csdn"theme="simple"@H_404_108@>
用户名:@H_404_108@<s:textfieldname="usernaem"id="uname"@H_404_108@/>
@H_404_108@<spanid="cname"@H_404_108@></span@H_404_108@>
密码:@H_404_108@<s:textfieldname="userpass"id="upass"@H_404_108@/>
邮箱:@H_404_108@<s:textfieldname="useremial"id="uemail"@H_404_108@/>
@H_404_108@<s:submitvalue="注册"@H_404_108@/>
@H_404_108@</s:form@H_404_108@>
<%@pagelanguage="java"import="java.util.*"pageEncoding="UTF-8"%>
<%@tagliburi="/struts-tags"prefix="s"%>
<%
Stringpath=request.getContextPath();
StringbasePath=request.getScheme()+"://"
+request.getServerName()+":"+request.getServerPort()
+path+"/";
%>
@H_404_108@<!DOCTYPE@H_404_108@HTMLPUBLIC@H_404_108@"-//W3C//DTDHTML4.01Transitional//EN">
@H_404_108@<basehref="<%=basePath%>"@H_404_108@>
@H_404_108@<title@H_404_108@>MyJSP'index.jsp'startingpage@H_404_108@</title@H_404_108@>
@H_404_108@<Metahttp-equiv="pragma"content="no-cache"@H_404_108@>
@H_404_108@<Metahttp-equiv="cache-control"content="no-cache"@H_404_108@>
@H_404_108@<Metahttp-equiv="expires"content="0"@H_404_108@>
@H_404_108@<Metahttp-equiv="keywords"content="keyword1,keyword3"@H_404_108@>
@H_404_108@<Metahttp-equiv="description"content="Thisismypage"@H_404_108@>
<!--
<linkrel="stylesheet"type="text/css"href="styles.css">
-->
@H_404_108@<scripttype="text/javascript"
src="${pageContext.request.contextPath}/js/util.js"@H_404_108@></script@H_404_108@>
@H_404_108@<scripttype="text/javascript"
src="${pageContext.request.contextPath}/js/user/reg.js"@H_404_108@></script@H_404_108@>
。。。。。。。。。
然后是js文件
//通过id获取dom对象
function$(id){
returndocument.getElementById(id);
}
//创建XMLHttpRequest对象
functioncreateXHR(){
//声明
varxhr;
//IE浏览器XMLHTTP组件的名称
varaVertion=["MSXML2.XMLHttp.5.0","Microsoft.XMLHttp"];
try{
//firefoxopera等浏览器
xhr=newXMLHttpRequest();
}catch(ex){
for(vari=0;i<aVertion.lengrh;i++){
try{
xmlHttpRequest=newActiveXObject(aVersion[i]);
returnxmlHttpRequest;
}catch(ex){
continue;
}
}
}
returnxhr;
}
window.onload=function(){
//获取id="uname"节点对象
varunameDom=$("uname");
//为节点注册onblur事件
unameDom.onblur=function(){
varcontent="name="+unameDom.value;
//封装请求的url路径
varurl="./csdn/UserAction_checkName.action?time="+newDate().getTime();
//获取创建的xhr对象(XMLHTTPRequest对象)
varxhr=createXHR();
//事件处理函数触发器
xhr.onreadystatechange=function(){
if(xhr.readyState==4){//状态码返回4处理完毕(这样才能使用xhr.responseText获取返回的结果)
if(xhr.status==200||xhr.status==304){//服务器返回的状态码200一切ok304服务器没有被修改
//ajax请求之后再这里做相应的处理
$("cname").innerHTML=xhr.responseText;
//如果接收的是XML文件就用responseXML;
}
}
};
//打开请求
xhr.open("POST",true);
//如果用POST请求向服务器发送数据,需要将“Content-type”的首部
//设置为“application/x-www-form-urlencoded”它会告知服务器正在发送数据,并且数据已经符合URL编码了
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
//发送请求
xhr.send(content);
};
};
@H_404_108@<?xmlversion="1.0"encoding="UTF-8"@H_404_108@?>
@H_404_108@<!DOCTYPE@H_404_108@strutsPUBLIC
@H_404_108@"-//ApacheSoftwareFoundation//DTDStrutsConfiguration2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd"@H_404_108@>
@H_404_108@<struts@H_404_108@>
@H_404_108@<includefile="www/csdn/project/resource/struts-constant.xml"@H_404_108@/>
@H_404_108@<packagename="test"namespace="/csdn"extends="struts-default"@H_404_108@>
@H_404_108@<actionname="UserAction_*"class="www.csdn.project.action.UserAction"method="{1}"@H_404_108@>
@H_404_108@<resultname="reg"type="plainText"@H_404_108@>
@H_404_108@<paramname="location"@H_404_108@>/sc.jsp@H_404_108@</param@H_404_108@>
@H_404_108@<paramname="charSet"@H_404_108@>UTF-8@H_404_108@</param@H_404_108@>
@H_404_108@</result@H_404_108@>
@H_404_108@</action@H_404_108@>
@H_404_108@</package@H_404_108@>
@H_404_108@</struts@H_404_108@>
packagewww.csdn.project.action;
importjava.io.IOException;
importjava.io.PrintWriter;
importjavax.servlet.http.HttpServletResponse;
importorg.apache.struts2.ServletActionContext;
importcom.opensymphony.xwork2.ActionSupport;
publicclassUserActionextendsActionSupport{
/**
*
*/
privatestaticfinallongserialVersionUID=1L;
privateStringname;
publicStringgetName(){
returnname;
}
publicvoidsetName(Stringname){
this.name=name;
}
publicStringcheckName(){
HttpServletResponseresponse=ServletActionContext.getResponse();//获取response对象
response.setContentType("text/html;charset=utf-8");//设置相应文档类型
PrintWriterout=null;//声明输出的out对象
try{
out=response.getWriter();//根据response对象获取out对象
}catch(IOExceptione){
e.printStackTrace();
}
if("xiao".equals(name)){
}else{
out.print("用户名可以使用");
}
out.flush();//立即写入
out.close();//关闭
return"reg";
}
}
ajax_返回xml数据的处理(包括分页)(数据库自己建立,在DAO层和service层实现用hibernate)
如图项目结构
连接数据库
数据库在相应层实现就行
<%@pagelanguage="java"import="java.util.*"pageEncoding="UTF-8"%>
<%@tagliburi="/struts-tags"prefix="s"%>
<%
Stringpath=request.getContextPath();
StringbasePath=request.getScheme()+"://"
+request.getServerName()+":"+request.getServerPort()
+path+"/";
%>
@H_404_108@<!DOCTYPE@H_404_108@HTMLPUBLIC@H_404_108@"-//W3C//DTDHTML4.01Transitional//EN">
@H_404_108@<basehref="<%=basePath%>"@H_404_108@>
@H_404_108@<title@H_404_108@>MyJSP'index.jsp'startingpage@H_404_108@</title@H_404_108@>
@H_404_108@<Metahttp-equiv="pragma"content="no-cache"@H_404_108@>
@H_404_108@<Metahttp-equiv="cache-control"content="no-cache"@H_404_108@>
@H_404_108@<Metahttp-equiv="expires"content="0"@H_404_108@>
@H_404_108@<Metahttp-equiv="keywords"content="keyword1,keyword3"@H_404_108@>
@H_404_108@<Metahttp-equiv="description"content="Thisismypage"@H_404_108@>
<!--
<linkrel="stylesheet"type="text/css"href="styles.css">
-->
@H_404_108@<divalign="center"@H_404_108@>
@H_404_108@<ahref="${pageContext.request.contextPath}/csdn/UserAction_login.action"@H_404_108@>进入后台@H_404_108@</a@H_404_108@>
<%@pagelanguage="java"import="java.util.*"pageEncoding="UTF-8"%>
<%@tagliburi="/struts-tags"prefix="s"%>
<%
Stringpath=request.getContextPath();
StringbasePath=request.getScheme()+"://"
+request.getServerName()+":"+request.getServerPort()
+path+"/";
%>
@H_404_108@<!DOCTYPE@H_404_108@HTMLPUBLIC@H_404_108@"-//W3C//DTDHTML4.01Transitional//EN">
@H_404_108@<basehref="<%=basePath%>"@H_404_108@>
@H_404_108@<title@H_404_108@>MyJSP'index.jsp'startingpage@H_404_108@</title@H_404_108@>
@H_404_108@<Metahttp-equiv="pragma"content="no-cache"@H_404_108@>
@H_404_108@<Metahttp-equiv="cache-control"content="no-cache"@H_404_108@>
@H_404_108@<Metahttp-equiv="expires"content="0"@H_404_108@>
@H_404_108@<Metahttp-equiv="keywords"content="keyword1,keyword3"@H_404_108@>
@H_404_108@<Metahttp-equiv="description"content="Thisismypage"@H_404_108@>
<!--
<linkrel="stylesheet"type="text/css"href="styles.css">
-->
@H_404_108@<scripttype="text/javascript"src="${pageContext.request.contextPath}/js/util.js"@H_404_108@></script@H_404_108@>
@H_404_108@<scripttype="text/javascript"src="${pageContext.request.contextPath}/js/user/user_checkName.js"@H_404_108@></script@H_404_108@>
@H_404_108@<scripttype="text/javascript"src="${pageContext.request.contextPath}/js/user/user_query.js"@H_404_108@></script@H_404_108@>
@H_404_108@<divalign="center"@H_404_108@>
@H_404_108@<divstyle="border:1px;width:600px;height:400px;"@H_404_108@>
@H_404_108@<tablewidth="300px"@H_404_108@>
用户名:
@H_404_108@<s:textfieldid="uname"name="username"theme="simple"@H_404_108@></s:textfield@H_404_108@>
@H_404_108@<tdstyle="color:red;font-size:10px;"id="cname"@H_404_108@>
密码:
@H_404_108@<s:passwordid="upass"name="userpass"theme="simple"@H_404_108@></s:password@H_404_108@>
@H_404_108@<tdcolspan="3"style="text-align:center;"@H_404_108@>
@H_404_108@<s:ahref="#"theme="simple"@H_404_108@>注册@H_404_108@</s:a@H_404_108@>
@H_404_108@</table@H_404_108@>
@H_404_108@<span@H_404_108@>不使用它@H_404_108@</span@H_404_108@>
@H_404_108@<s:urlid="user_query"namespace="/csdn"action="UserAction_query"@H_404_108@></s:url@H_404_108@>
@H_404_108@<s:ahref="%{user_query}"@H_404_108@>查询所有用户@H_404_108@</s:a@H_404_108@>
@H_404_108@<inputtype="button"value="查询所有用户"id="queryBtn"@H_404_108@>
@H_404_108@<h3@H_404_108@>显示所有的用户信息@H_404_108@</h3@H_404_108@>
@H_404_108@<tableborder="1px"cellpadding="0"cellspacing="0"@H_404_108@>
@H_404_108@<th@H_404_108@>@H_404_108@<inputtype="checkBox"id="qx"@H_404_108@/></th@H_404_108@>
@H_404_108@<th@H_404_108@>序号@H_404_108@</th@H_404_108@>
@H_404_108@<th@H_404_108@>姓名@H_404_108@</th@H_404_108@>
@H_404_108@<th@H_404_108@>性别@H_404_108@</th@H_404_108@>
@H_404_108@<th@H_404_108@>职位@H_404_108@</th@H_404_108@>
@H_404_108@<th@H_404_108@>操作@H_404_108@</th@H_404_108@>
@H_404_108@</thead@H_404_108@>
@H_404_108@<tbodyid="showUsers"@H_404_108@></tbody@H_404_108@>
@H_404_108@</table@H_404_108@>
window.onload=function(){
varuserBtnDom=$("userBtn");
userBtnDom.onclick=function(){
//封装请求的数据
varcontent="pagination.nowPage="+1;
//封装请求的路径
varurl="./csdn/UserAction_pagexml.action?time="
+newDate().getTime();
//调用封装的ajax的post请求
sendPost(content,disposeFail);
//成功处理函数
functiondisposeSuccess(xhr){
//接受相应的xml数据并且返回xmlDocument对象
varxmlDoc=xhr.responseXML;
//获取根对象
varroot=xmlDoc.documentElement;
//获取根节点中所有的Member节点对象
varusers=root.getElementsByTagName("user");
//显示数据
showUsers(users);
$("firstPage").onclick=function(){
content="pagination.nowPage="+1;
//发送请求的时候
sendPost(content,disposeFail);
};
$("backPage").onclick=function(){
content="pagination.nowPage="+eval(root.getAttribute("nowpage")+"-"+1);
//发送请求的时候
sendPost(content,disposeFail);
};
$("nextPage").onclick=function(){
content="pagination.nowPage="+eval(root.getAttribute("nowpage")+"+"+1);
//发送请求的时候
sendPost(content,disposeFail);
};
$("lastPage").onclick=function(){
content="pagination.nowPage="+root.getAttribute("countPage");
//发送请求的时候
sendPost(content,disposeFail);
};
}
//失败处理函数
functiondisposeFail(xhr){
alert("失败处理");
}
};
};
varupTr=null;
functionshowUsers(users){
//清空操作
if($("showUsers").hasChildNodes()){
for(varjj=0;jj<$("showUsers").childNodes.length;){
$("showUsers").removeChild($("showUsers").childNodes[jj]);
}
}
for(vari=0;i<users.length;i++){
varuser=users[i];
vartr=document.createElement("tr");
vartd1=document.createElement("td");
varinput=document.createElement("input");
input.setAttribute("type","checkBox");
input.setAttribute("value",user.getAttribute("id"));
td1.appendChild(input);
vartd2=document.createElement("td");
td2.appendChild(document.createTextNode(user.getAttribute("id")));
vartd3=document.createElement("td");
td3.appendChild(document.createTextNode(user
.getElementsByTagName("name")[0].firstChild.nodeValue));
vartd4=document.createElement("td");
td4.appendChild(document.createTextNode(user
.getElementsByTagName("sex")[0].firstChild.nodeValue));
vartd5=document.createElement("td");
td5.appendChild(document.createTextNode(user
.getElementsByTagName("role")[0].firstChild.nodeValue));
vartd6=document.createElement("td");
//创建修改按钮
varupdateBtn=document.createElement("button");
//为按钮添加文本节点
updateBtn.appendChild(document.createTextNode("编辑"));
updateBtn.onclick=function(){
upTr=this.parentNode.parentNode;
vartds=upTr.childNodes;
for(vari=0;i<tds.length;i++){
vartd=tds[i];
if(td.nodeType==1){
if(i==0){
domUserName.value=td.firstChild.nodeValue;
}elseif(i==1){
domUserSex.value=td.lastChild.nodeValue;
}elseif(i==2){
domUserRole.value=td.childNodes[0].nodeValue;
}
}
};
};
td6.appendChild(updateBtn);
tr.appendChild(td1);
tr.appendChild(td2);
tr.appendChild(td3);
tr.appendChild(td4);
tr.appendChild(td5);
tr.appendChild(td6);
$("showUsers").appendChild(tr);
}
}
functionsendPost(content,fail){
//ajax处理操作
//创建xhr对象
varxhr=createXHR();
//触发器
xhr.onreadystatechange=function(){
if(xhr.readyState==4){
if(xhr.status==200||xhr.status==304){
success(xhr);
}else{
fail(xhr);
}
}
};
//打开请求
xhr.open("POST","application/x-www-form-urlencoded");
//发送请求
xhr.send(content);
}
@H_404_108@<?xmlversion="1.0"encoding="UTF-8"@H_404_108@?>
@H_404_108@<!DOCTYPE@H_404_108@strutsPUBLIC
@H_404_108@"-//ApacheSoftwareFoundation//DTDStrutsConfiguration2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd"@H_404_108@>
@H_404_108@<struts@H_404_108@>
@H_404_108@<includefile="www/csdn/project/resource/struts-constant.xml"@H_404_108@/>
@H_404_108@<packagename="test"namespace="/csdn"extends="struts-default"@H_404_108@>
@H_404_108@<actionname="UserAction_*"class="www.csdn.project.action.UserAction"method="{1}"@H_404_108@>
@H_404_108@<resultname="login"@H_404_108@>/WEB-INF/page/user/user_list.jsp@H_404_108@</result@H_404_108@>
@H_404_108@<resultname="xml"type="plainText"@H_404_108@>
@H_404_108@<paramname="location"@H_404_108@>./index.jsp@H_404_108@</param@H_404_108@>
@H_404_108@<paramname="charSet"@H_404_108@>UTF-8@H_404_108@</param@H_404_108@>
@H_404_108@</result@H_404_108@>
@H_404_108@</action@H_404_108@>
@H_404_108@</package@H_404_108@>
@H_404_108@</struts@H_404_108@>
packagewww.csdn.project.util;
importjava.util.ArrayList;
importjava.util.List;
/**
*
*@authorkun
*
*
*@param<T>
*/
publicclassPagination<T>extendsBaseHibernateDAO{
//每页显示的记录数
privatestaticfinalIntegerPAGESIZE=5;
//总页数
privateIntegercountPage;
//当前页
privateIntegernowPage;
//总记录数
privateIntegercountRecond;
//当前页数据
privateList<T>entities;
/**
*默认构造器
*/
publicPagination(){
super();
}
/**
*带有参数的构造器
*
*@paramclassName
*@paramnowPage
*/
publicPagination(Class<T>className,intnowPage){
this.countRecond=getCountRecord(className);
this.countPage=this.countRecond%PAGESIZE==0?this.countRecond
/PAGESIZE:this.countRecond/PAGESIZE+1;
//关于当前的处理
if(nowPage<=1){
this.nowPage=1;
}else{
if(nowPage>=this.countPage){
this.nowPage=this.countPage;
}else{
this.nowPage=nowPage;
}
}
this.entities=getNowPageInfo(this.nowPage,className);
}
publicIntegergetCountPage(){
returncountPage;
}
publicvoidsetCountPage(IntegercountPage){
this.countPage=countPage;
}
publicIntegergetNowPage(){
returnnowPage;
}
publicvoidsetNowPage(IntegernowPage){
this.nowPage=nowPage;
}
publicIntegergetCountRecond(){
returncountRecond;
}
publicvoidsetCountRecond(IntegercountRecond){
this.countRecond=countRecond;
}
publicList<T>getEntities(){
returnentities;
}
publicvoidsetEntities(List<T>entities){
this.entities=entities;
}
/**
*等到总记录数
*
*@paramclassName
*@return
*/
publicIntegergetCountRecord(Class<T>className){
inti=0;
try{
i=Integer.parseInt(this.getSession().createQuery(
"selectcount(c)from"+className.getName()+"c")
.uniqueResult().toString());
}catch(Exceptione){
e.printStackTrace();
}finally{
HiberSessionFactory.closeSession();
}
returni;
}
/**
*获取当前页的信息
*
*@paramnowpage
*@paramclassName
*@return
*/
@SuppressWarnings("unchecked")
publicList<T>getNowPageInfo(Integernowpage,Class<T>className){
List<T>entities=newArrayList<T>();
try{
entities=this.getSession().createCriteria(className)
.setFirstResult((nowpage-1)*PAGESIZE).setMaxResults(
PAGESIZE).list();
}catch(Exceptione){
e.printStackTrace();
}finally{
HiberSessionFactory.closeSession();
}
returnentities;
}
}
最后在UserAction.java文件中实现XML数据处理:
packagewww.csdn.project.action;
importjava.io.IOException;
importjava.io.PrintWriter;
importjavax.servlet.http.HttpServletResponse;
importorg.apache.struts2.ServletActionContext;
importwww.csdn.project.domain.User;
importwww.csdn.project.util.Pagination;
importcom.opensymphony.xwork2.ActionSupport;
publicclassUserActionextendsActionSupport{
/**
*
*/
privatestaticfinallongserialVersionUID=1L;
privatePagination<User>pagination;
publicvoidsetPagination(Pagination<User>pagination){
this.pagination=pagination;
}
publicStringpagexml(){
//当前页信息
pagination=newPagination<User>(User.class,pagination.getNowPage());
HttpServletResponseresponse=ServletActionContext.getResponse();
response.setContentType("text/xml;charset=utf-8");
PrintWriterout=null;
try{
out=response.getWriter();
out.println("<?xmlversion='1.0'encoding='UTF-8'?>");
out.print("<usersnowpage='"+pagination.getNowPage()+"'countPage='"+pagination.getCountPage()+"'countRecond='"+pagination.getCountRecond()+"'>");
for(Userentity:pagination.getEntities()){
out.print("<userid='"+entity.getId()+"'>");
out.print("<name>");
out.print(entity.getName());
out.print("</name>");
out.print("<sex>");
out.print(entity.getSex());
out.print("</sex>");
out.print("<role>");
out.print(entity.getRole());
out.print("</role>");
out.print("</user>");
}
out.print("</users>");
out.flush();
out.close();
}catch(IOExceptione){
e.printStackTrace();
}
return"xml";
}
publicStringlogin(){
return"login";
}
}