<%@page contentType="text/html;charset=UTF-8" language="java"%>
<%@page pageEncoding="UTF-8" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>AjaxTest</title>
</head>
<script language="JavaScript" type="text/javascript">
var XMLHttpReq=false;
function createXMLHttpRequest(){
if(window.XMLHttpRequest){
XMLHttpReq=new XMLHttpRequest();
}
else if(window.ActiveXObject){
try{
XMLHttpReq=new ActiveXObject("Msxml2.XMLHTTP");
}catch(e){
try{
XMLHttpReq=new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){}
}
}
}
function sendRequest(url){
createXMLHttpRequest();
XMLHttpReq.open("GET",url,true);
XMLHttpReq.onreadystatechange=processResponse;
XMLHttpReq.send(null);
}
function processResponse(){
if(XMLHttpReq.readyState==4){
if(XMLHttpReq.status==200){
var res=XMLHttpReq.responseXML.getElementsByTagName("res")[0].firstChild.data;
window.alert(res);
}else{
window.alert("您所请求的页面有异常");
}
}
}
function userCheck(){
var uname=document.myform.uname.value;
var psw=document.myform.psw.value;
if(uname==""){
window.alert("用户名不能为空。");
document.myform.uname.focus();
return false;
}
else{
sendRequest('login?uname=' + uname + '&psw=' + psw);
}
}
</script>
<body>
<center>
<h1>用户登录</h1>
<form action="" method="POST" name="myform">
用户名:<input type="text"size="15" name="uname"> <p>
密码:<input type="password" size="15" name="psw"> <p>
<input type="button" value="登录" onclick="userCheck()">
</form>
</center>
</body>
</html>
对应的Servlet为login.java:
package user;
import java.io.*;
import java.net.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class login extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String uname=request.getParameter("uname");
String psw=request.getParameter("psw");
out.println("<response>");
if(uname.equals("wanggang") && psw.equals("123456")){
out.println("<res>"+"热烈的欢迎!"+"</res>");
}else{
out.println("<res>"+"对不起,登录失败!"+"</res>");
}
out.println("</response>");
out.close();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request,response);
}
}