在java Web中如何用Ajax实现用户名已存在
我给你做一个例子:希望能帮到你。
实现的功能:注册页面上当输入“lixin”时,显示该用户已被注册。其他的名称无所谓。希望能帮到你。欢迎追问。
一个简单的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>
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<script type="text/javascript" language="javascript">
//根据浏览器的不同创建不同的XMLHttpRequest
function createXmlHttpRequest(){
var xmlreq=false;
if(window.XMLHttpRequest){
xmlreq=new XMLHttpRequest();
}else if(window.ActiveXobject){
try{
xmlreq = new ActiveXobject("Msxm12.XMLHTTP");
}catch(e1){
try{
xmlreq = new ActiveXobject("Miscoft.XMLHTTP");
}catch(e2){
}
}
}
return xmlreq;
}
//
function usernameCheck(){
var username = document.all.username.value;//获得text的值
var request = createXmlHttpRequest();//创建request的对象
request.open("post","servlet/ValidationServlet?username="+username);
request.send();
request.onreadystatechange = function(){
if(request.readyState==4&request.status==200)
{
var value = request.responseText;
if(value=="true"){
document.all.unc.innerHTML="该用户名已经被注册";}
}else{
document.all.unc.innerHTML="该用户可以注册";
}
}}
</script>
</head>
<body>
用户姓名:<input type ="text" name="username" onblur="usernameCheck()" /><font color="red" size="-1" id="unc"></font>
<br>
用户密码:<input type ="password" name= "userpw" />
</body>
</html>
用到的Servlet:
package sample;
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 ValidationServlet extends HttpServlet {
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
String username = request.getParameter("username");
if(username.equals("lixin")){
response.getWriter().print("true");}
else{
response.getWriter().print("false");
}
}
}