Ajax几个简单的案例(ajax_用户唯一验证、ajax_返回xml数据的处理(包括分页处理)
当然开发的前提是把相应的包导入项目中(开发环境myeclipse)
ajax_用户唯一验证(servlet):
如图在myeclipse中的ajax_servlet项目中的index.jsp实现页面的显示:
Index.jsp代码:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.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">
-->
<script type="text/javascript"
src="${pageContext.request.contextPath }/js/util.js"></script>
<script type="text/javascript"
src="${pageContext.request.contextPath }/js/user/reg.js"></script>
</head>
<body>
<div align="center">
<form action="">
用户名:<input type="text" id="uname" /><span id="cname"></span><br>
密 码:<input type="password" id="upass" /><br> <input
type="submit" value="注册" />
</form>
</div>
</body>
</html>
然后在webroot下新建一个js文件夹,这个里面写我们的js代码实现ajax使用
在util.js中封装了发送和接收的请求和一些必要的代码
Util.js文件代码:
//通过id获取dom对象
function $(id){
return document.getElementById(id);
}
//创建XMLHttpRequest对象
function createXHR(){
//声明
var xhr;
//IE 浏览器XMLHTTP 组件的名称
var aVertion =["MSXML2.XMLHttp.5.0","MSXML2.XMLHttp.4.0","MSXML2.XMLHttp.3.0","MSXML2.XMLHttp.2.0","Microsoft.XMLHttp"];
try{
//firefox opera等浏览器
xhr=new XMLHttpRequest();
}catch(ex){
for (var i=0;i<aVertion.lengrh;i++){
try{
xmlHttpRequest=new ActiveXObject(aVersion[i]);
return xmlHttpRequest;
}catch(ex){
continue;
}
}
}
return xhr;
}
var xhr = createXHR();
function sendPost(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", url, true);
// 设置类型
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
// 发送请求
xhr.send(content);
}
然后再user下的reg.js中写要完成的代码
Reg.js文件代码:
window.οnlοad=function(){
//获取id="uname"节点对象
var unameDom=$("uname");
//为节点注册onblur事件
unameDom.οnblur=function(){
//根据value属性获取穿的的值并且拼成传递的参数
var content ="name="+unameDom.value;
//封装请求的url路径
var url="./servlet/regUser.do?time="+new Date().getTime();
sendPost(content, url, disposeSuccess, disposeFail);
function disposeSuccess(){
$("cname").innerHTML=xhr.responseText;
}
function disposeFail(){
alert("请求失败");
}
};
};
最后在src下建立action处理方法
UserAction.java文件代码:
package www.csdn.net.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class UserServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String name=request.getParameter("name");
System.out.println("===="+name);
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
if("xiao".equals(name)){
out.print("用户已经存在");//输出文本
}else{
out.print("用户名可以使用");
}
out.flush();
out.close();
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}
}
这样就完成了,发布到tomcat服务器上然后用火狐浏览器测试就可以了
ajax_用户唯一验证(struts2)
如图所示;
首先实现页面的代码:
Index.jsp文件代码:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<%
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 'index.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">
-->
<script type="text/javascript"
src="${pageContext.request.contextPath }/js/util.js"></script>
<script type="text/javascript"
src="${pageContext.request.contextPath }/js/user/reg.js"></script>
</head>
<body>
<div align="center">
<h3>注册页面</h3>
</div>
<div align="center">
<s:form action="regUser" namespace="/csdn" theme="simple">
用户名:<s:textfield name="usernaem" id="uname" />
<span id="cname"></span>
<br>
密 码:<s:textfield name="userpass" id="upass" />
<br>
邮 箱:<s:textfield name="useremial" id="uemail" />
<br>
<s:submit value="注册" />
</s:form>
</div>
</body>
</html>
Sc.jsp文件代码:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<%
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 'index.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">
-->
<script type="text/javascript"
src="${pageContext.request.contextPath }/js/util.js"></script>
<script type="text/javascript"
src="${pageContext.request.contextPath }/js/user/reg.js"></script>
</head>
<body>
。。。。。。。。。
</body>
</html>
然后是js文件
Util.js文件代码:
//通过id获取dom对象
function $(id){
return document.getElementById(id);
}
//创建XMLHttpRequest对象
function createXHR(){
//声明
var xhr;
//IE 浏览器XMLHTTP 组件的名称
var aVertion =["MSXML2.XMLHttp.5.0","MSXML2.XMLHttp.4.0","MSXML2.XMLHttp.3.0","MSXML2.XMLHttp.2.0","Microsoft.XMLHttp"];
try{
//firefox opera等浏览器
xhr=new XMLHttpRequest();
}catch(ex){
for (var i=0;i<aVertion.lengrh;i++){
try{
xmlHttpRequest=new ActiveXObject(aVersion[i]);
return xmlHttpRequest;
}catch(ex){
continue;
}
}
}
return xhr;
}
Reg.js文件代码:
window.οnlοad=function(){
//获取id="uname"节点对象
var unameDom=$("uname");
//为节点注册onblur事件
unameDom.οnblur=function(){
//根据value属性获取穿的的值并且拼成传递的参数
var content ="name="+unameDom.value;
//封装请求的url路径
var url="./csdn/UserAction_checkName.action?time="+new Date().getTime();
//获取创建的xhr对象(XMLHTTPRequest对象)
var xhr=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",url,true);
//如果用POST请求向服务器发送数据,需要将“Content-type”的首部
//设置为“application/x-www-form-urlencoded”它会告知服务器正在发送数据,并且数据已经符合URL编码了
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
//发送请求
xhr.send(content);
};
};
Struts.xml文件代码:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<include file="www/csdn/project/resource/struts-constant.xml"/>
<package name="test" namespace="/csdn" extends="struts-default">
<action name="UserAction_*" class="www.csdn.project.action.UserAction" method="{1}">
<result name="reg" type="plainText">
<param name="location">/sc.jsp</param>
<param name="charSet">UTF-8</param>
</result>
</action>
</package>
</struts>
最后UserAction.java文件代码:
package www.csdn.project.action;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class UserAction extends ActionSupport{
/**
*
*/
private static final long serialVersionUID = 1L;
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String checkName(){
HttpServletResponse response=ServletActionContext.getResponse();//获取response对象
response.setContentType("text/html;charset=utf-8");//设置相应文档类型
PrintWriter out=null;//声明输出的out对象
try {
out=response.getWriter();//根据response对象获取out对象
} catch (IOException e) {
e.printStackTrace();
}
if("xiao".equals(name)){
out.print("用户已经存在");//输出文本
}else{
out.print("用户名可以使用");
}
out.flush();//立即写入
out.close();//关闭
return "reg";
}
}
ajax_返回xml数据的处理(包括分页)(数据库自己建立,在DAO层和service层实现用hibernate)
如图项目结构
连接数据库
数据库在相应层实现就行
首先实现页面的显示
Index.jsp文件代码:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<%
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 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<div align="center">
<a href="${pageContext.request.contextPath }/csdn/UserAction_login.action">进入后台</a>
</div>
</body>
</html>
Cindex.jsp文件代码:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<%
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 'index.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">
-->
<script type="text/javascript" src="${pageContext.request.contextPath }/js/util.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath }/js/user/user_checkName.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath }/js/user/user_query.js"></script>
</head>
<body>
<div align="center">
<div style="border: 1px; width: 600px; height: 400px;">
<table width="300px">
<tr>
<td>
用户名:
</td>
<td>
<s:textfield id="uname" name="username" theme="simple"></s:textfield>
</td>
<td style="color: red; font-size: 10px;" id="cname">
</td>
</tr>
<tr>
<td>
密 码:
</td>
<td>
<s:password id="upass" name="userpass" theme="simple"></s:password>
</td>
<td>
</td>
</tr>
<tr>
<td colspan="3" style="text-align: center;">
<s:a href="#" theme="simple">注册</s:a>
</td>
</tr>
</table>
</div>
<div>
<span>不使用它</span>
<s:url id="user_query" namespace="/csdn" action="UserAction_query"></s:url>
<s:a href="%{user_query}">查询所有用户</s:a>
</div>
<br/>
<div>
<input type="button" value="查询所有用户" id="queryBtn">
</div>
<div>
<h3>显示所有的用户信息</h3>
<table border="1px" cellpadding="0" cellspacing="0">
<thead>
<th><input type="checkbox" id="qx"/></th>
<th>序号</th>
<th>姓名</th>
<th>性别</th>
<th>职位</th>
<th>操作</th>
</thead>
<tbody id="showUsers"></tbody>
</table>
</div>
</div>
</body>
</html>
userpage_xml.js文件:(这里实现了分页)
window.onload = function() {
var userBtnDom = $("userBtn");
userBtnDom.onclick = function() {
// 封装请求的数据
var content = "pagination.nowPage=" + 1;
// 封装请求的路径
var url = "./csdn/UserAction_pagexml.action?time="
+ new Date().getTime();
// 调用封装的ajax的post请求
sendPost(content, url, disposeSuccess, disposeFail);
// 成功处理函数
function disposeSuccess(xhr) {
// 接受相应的xml数据 并且返回 xmlDocument对象
var xmlDoc = xhr.responseXML;
// 获取根对象
var root = xmlDoc.documentElement;
// 获取根节点中所有的Member节点对象
var users = root.getElementsByTagName("user");
// 显示数据
showUsers(users);
$("firstPage").οnclick=function(){
content ="pagination.nowPage="+1;
//发送请求的时候
sendPost(content, url, disposeSuccess, disposeFail);
};
$("backPage").οnclick=function(){
content ="pagination.nowPage="+eval(root.getAttribute("nowpage")+"-"+1);
//发送请求的时候
sendPost(content, url, disposeSuccess, disposeFail);
};
$("nextPage").οnclick=function(){
content ="pagination.nowPage="+eval(root.getAttribute("nowpage")+"+"+1);
//发送请求的时候
sendPost(content, url, disposeSuccess, disposeFail);
};
$("lastPage").οnclick=function(){
content ="pagination.nowPage="+root.getAttribute("countPage");
//发送请求的时候
sendPost(content, url, disposeSuccess, disposeFail);
};
}
// 失败处理函数
function disposeFail(xhr) {
alert("失败处理");
}
};
};
var upTr =null;
function showUsers(users) {
// 清空操作
if ($("showUsers").hasChildNodes()) {
for (var jj = 0; jj < $("showUsers").childNodes.length;) {
$("showUsers").removeChild($("showUsers").childNodes[jj]);
}
}
for (var i = 0; i < users.length; i++) {
var user = users[i];
var tr = document.createElement("tr");
var td1 = document.createElement("td");
var input = document.createElement("input");
input.setAttribute("type", "checkbox");
input.setAttribute("value", user.getAttribute("id"));
td1.appendChild(input);
var td2 = document.createElement("td");
td2.appendChild(document.createTextNode(user.getAttribute("id")));
var td3 = document.createElement("td");
td3.appendChild(document.createTextNode(user
.getElementsByTagName("name")[0].firstChild.nodeValue));
var td4 = document.createElement("td");
td4.appendChild(document.createTextNode(user
.getElementsByTagName("sex")[0].firstChild.nodeValue));
var td5 = document.createElement("td");
td5.appendChild(document.createTextNode(user
.getElementsByTagName("role")[0].firstChild.nodeValue));
var td6 = document.createElement("td");
//创建修改按钮
var updateBtn = document.createElement("button");
//为按钮添加文本节点
updateBtn.appendChild(document.createTextNode("编辑"));
updateBtn.onclick = function(){
upTr = this.parentNode.parentNode;
var tds = upTr.childNodes;
for(var i=0;i<tds.length;i++){
var td = tds[i];
if(td.nodeType==1){
if(i==0){
domUserName.value=td.firstChild.nodeValue;
}else if(i==1){
domUserSex.value=td.lastChild.nodeValue;
}else if(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);
}
}
function sendPost(content, url, success, fail) {
// ajax处理操作
// 创建xhr对象
var xhr = createXHR();
// 触发器
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status == 200 || xhr.status == 304) {
success(xhr);
} else {
fail(xhr);
}
}
};
// 打开请求
xhr.open("POST", url, true);
// 设置类型
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
// 发送请求
xhr.send(content);
}
Struts.xml文件代码:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<include file="www/csdn/project/resource/struts-constant.xml"/>
<package name="test" namespace="/csdn" extends="struts-default">
<action name="UserAction_*" class="www.csdn.project.action.UserAction" method="{1}">
<result name="login">/WEB-INF/page/user/user_list.jsp</result>
<result name="xml" type="plainText">
<param name="location">./index.jsp</param>
<param name="charSet">UTF-8</param>
</result>
</action>
</package>
</struts>
分页的实现是在util层中封装的实现分页的代码:
Pagination.java文件代码:
package www.csdn.project.util;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author kun
*
*
* @param <T>
*/
public class Pagination<T> extends BaseHibernateDAO {
// 每页显示的记录数
private static final Integer PAGESIZE = 5;
// 总页数
private Integer countPage;
// 当前页
private Integer nowPage;
// 总记录数
private Integer countRecond;
// 当前页数据
private List<T> entities;
/**
* 默认构造器
*/
public Pagination() {
super();
}
/**
* 带有参数的构造器
*
* @param className
* @param nowPage
*/
public Pagination(Class<T> className, int nowPage) {
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);
}
public Integer getCountPage() {
return countPage;
}
public void setCountPage(Integer countPage) {
this.countPage = countPage;
}
public Integer getNowPage() {
return nowPage;
}
public void setNowPage(Integer nowPage) {
this.nowPage = nowPage;
}
public Integer getCountRecond() {
return countRecond;
}
public void setCountRecond(Integer countRecond) {
this.countRecond = countRecond;
}
public List<T> getEntities() {
return entities;
}
public void setEntities(List<T> entities) {
this.entities = entities;
}
/**
* 等到总记录数
*
* @param className
* @return
*/
public Integer getCountRecord(Class<T> className) {
int i = 0;
try {
i = Integer.parseInt(this.getSession().createQuery(
"select count(c) from " + className.getName() + " c")
.uniqueResult().toString());
} catch (Exception e) {
e.printStackTrace();
} finally {
HiberSessionFactory.closeSession();
}
return i;
}
/**
* 获取当前页的信息
*
* @param nowpage
* @param className
* @return
*/
@SuppressWarnings("unchecked")
public List<T> getNowPageInfo(Integer nowpage, Class<T> className) {
List<T> entities = new ArrayList<T>();
try {
entities = this.getSession().createCriteria(className)
.setFirstResult((nowpage - 1) * PAGESIZE).setMaxResults(
PAGESIZE).list();
} catch (Exception e) {
e.printStackTrace();
} finally {
HiberSessionFactory.closeSession();
}
return entities;
}
}
最后在UserAction.java文件中实现XML数据处理:
UserAction.java文件代码:
package www.csdn.project.action;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import www.csdn.project.domain.User;
import www.csdn.project.util.Pagination;
import com.opensymphony.xwork2.ActionSupport;
public class UserAction extends ActionSupport{
/**
*
*/
private static final long serialVersionUID = 1L;
private Pagination<User> pagination;
public void setPagination(Pagination<User> pagination) {
this.pagination = pagination;
}
public String pagexml(){
//当前页信息
pagination = new Pagination<User>(User.class, pagination.getNowPage());
HttpServletResponse response = ServletActionContext.getResponse();
response.setContentType("text/xml;charset=utf-8");
PrintWriter out = null;
try {
out = response.getWriter();
out.println("<?xml version='1.0' encoding='UTF-8'?>");
out.print("<users nowpage='"+pagination.getNowPage()+"' countPage='"+pagination.getCountPage()+"' countRecond='"+pagination.getCountRecond()+"'>");
for(User entity : pagination.getEntities()){
out.print("<user id='"+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 (IOException e) {
e.printStackTrace();
}
return "xml";
}
public String login(){
return "login";
}
}