ajax和struts结合实现无刷新验证用户名是否存在
2007年07月08日 星期日 23:36<%@ page language="java" import="java.util.*" pageEncoding="gb2312"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<TITLE>Ajax验证用户名是否存在例子</TITLE>
<script>
//设一个变量
var XMLHttpReq=false;
//创建一个XMLHttpRequest对象
function createXMLHttpRequest(){
if(window.XMLHttpRequest){ //Mozilla
XMLHttpReq=new XMLHttpRequest();
}
else if(window.ActiveXObject){
try{
XMLHttpReq=new ActiveXObject("Msxml2.XMLHTTP");
}catch(e){
try{
XMLHttpReq=new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){}
}
}
}
//发送请求函数
function send(url){
createXMLHttpRequest();
XMLHttpReq.open("get",url,true);
XMLHttpReq.send(null);    //发送请求
}
function proce(){
adyState==4){ //对象状态
if(XMLHttpReq.status==200){//信息已成功返回,开始处理信息   
<!--测试读取xml开始-->
var sponseXML;
var ElementsByTagName("content")[0].firstChild.data;
window.alert(res);
<!--测试读取xml结束--> 
//var xmlReturn = sponseText;
//window.alert(xmlReturn);
}else{
window.alert("所请求的页面有异常");
}
}
}
//身份验证
function check(){
var ElementById("name").value;
if(name==""){
alert("请输入姓名!");
return false;
}
else{
//send('login?name='+name); 
send('login.do?name='+name);
}
}
</script>
</head>
<body>
<form action="login" method="post">
<table>
<tr><td>姓名: <input id="name" type="text" name="name"/><p>
<div id=load >正在验证用户名,请稍后……</div><p>
<input type="button" value="检测!" onClick="check()"/>
</td>
</tr>
</table>
</form>
</body>
</html>
structs-config配置:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN" "/dtds/struts-config_1_2.dtd">
<struts-config>
<data-sources />
<form-beans >
<form-bean name="loginForm" type="org.viman.struts.form.LoginForm" />
</form-beans>
<global-exceptions />
<global-forwards />
<action-mappings >
<action
attr
ibute="loginForm"
html怎么实现登录验证功能input="/login.jsp"
name="loginForm"
path="/login"
scope="request"
type="org.viman.struts.action.LoginAction" />
</action-mappings>
<message-resources parameter="org.viman.struts.ApplicationResources" />
</struts-config>
action实现(LoginAction.java):
package org.viman.struts.action;
import java.io.UnsupportedEncodingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.viman.struts.form.LoginForm;
/**
* MyEclipse Struts
* Creation date: 01-06-2007
*
* XDoclet definition:
* @struts.action path="/login" name="loginForm" input="/login.jsp" scope="request" validate="true"
*/
public class LoginAction extends Action {
/*
* Generated Methods
*/
/**
* Method execute
* @param mapping
* @param form
* @param request
* @param response
* @return ActionForward
*/
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
//LoginForm loginForm = (LoginForm) form;// TODO Auto-generated method stub
try {
request.setCharacterEncoding("gb2312");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
try{
String msgStr="";
response.setContentType("text/xml;charset=GB2312");
response.setHeader("Cache-Control","no-cache");
String name=(Parameter("name");
System.out.println("name = "+name);
if("gong".equals(name)){ //查数据库中有无该用户名
msgStr ="对不起,此用户名已经存在,请更换用户名注册!";
}else{
msgStr ="用户未被注册,可以使用!";
}
}catch(Exception ex){
return null;
}
============================================================================================================
第二种答案
用struts + ajax验证用户名是否存在的全部源码:
<%@ page contentType="text/html; charset=GBK" %>
<html>
<head>
<title>
ajax
</title>
</head>
<body bgcolor="#ffffff">
<h1>
<input name="username" type="text" maxlength="20" />
<input id="chk-name-btn" type="button" value="检测帐号" onclick="testName('<%=ContextPath()%>')" />
<div id="view_name"></div>
</h1>
</body>
</html>
<script language="javascript">
if (window
.ActiveXObject && !window.XMLHttpRequest) {
window.XMLHttpRequest=function() {
return new ActiveXObject((LowerCase().indexOf('msie 5') != -1) ? 'Microsoft.XMLHTTP' : 'Msxml2.XMLHTTP');
};
}//取得XMLHttpRequest对象
function testName(path){
//path是取得系统路径
var view_ElementById("view_name");
var req=new XMLHttpRequest();
if (req) {
if (adyState==4 && req.status==200) {//判断状态,4是已发送,200已完成
sponseText==0){
view_lor='green';
view_name.innerHTML='该用户名可以正常使用';
}else sponseText==1){
view_lor='red';
view_name.innerHTML='该用户名已经被使用';
}else{
view_lor='red';
view_name.innerHTML='该用户名含有非法字符!';
}
}
}
req.open('POST', path+'/ajax.do');//struts
//req.open('POST', path+'/ajax.servlet');//servlet
//req.open('POST', path+'/ajax.action');//webwork
req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
req.send("");//发送参数如果有参数req.send("username="+user_name);用request取得
}
}
</script>
这个jsp页面并没有取得用户名,就是演示一下。还有<div>可以换span,具体作用问美工吧。
接受ajax请求的action。
import org.apache.struts.action.*;
import javax.servlet.http.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
/**
* <p>Title:AjaxAction </p>
*/
public class AjaxAction extends Action {
public ActionForward execute(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception {
PrintWriter out = Writer();
out.print(1);//ajax取得都是字符的输出。如果数据量大的话,还可以用xml来发送和接受
return null;
}
}
<action type="test.whw.upload.AjaxAction" validate="false" scope="request"  path="/ajax"/>
----------------------------
如果是servlet
<servlet>
<servlet-name>AjaxServlet </servlet-name>
<servlet-class>servlet.AjaxServlet </servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>AjaxServlet </servlet-name>
<url-pattern>/AjaxServle
t .servlet</url-pattern>
</servlet-mapping>
AjaxServlet.java
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 AjaxServlet extends HttpServlet {
Logger log = Class());
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException,IOException {
response.setContentType("text/xml; charset=GBK");
PrintWriter out = Writer();
out.print(2);
}
}
//Process the HTTP Post request
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
//Process the HTTP Put request
public void doPut(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
//Process the HTTP Delete request
public void doDelete(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
}
//Clean up resources
public void destroy() {
}
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。