<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>login</title>
<script language="javascript">
//創建xmlhttprequest對象
var xmlHttp = false;
try{
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}catch(e){
try{
xmlHttp = new ActiveXObject("microsoft.XMLHTTP");
}catch(e1){
try{
xmlHttp = new XMLHttpRequest();
}catch(e2){
xmlHttp = false;
}
}
}
if(!xmlHttp)
{
alert("server is error");
}
function login()
{
var userName = document.getElementById("userName");
var pwd = document.getElementById("pwd");
if(userName.value == 0 || pwd.value == 0)
{
alert("請輸入用戶名或密碼!");
userName.focus();
return false;
}
else
{
//注意這個提交的地址,傳遞的參數都放在encodeURI()函數當中,它把字符串做爲一個uri進行編碼,最大的一個好處就是可以處理中文亂碼
var url="http://localhost:8080/ajaxXML/loginServlet?userName="+encodeURI(userName.value)+"&pwd="+encodeURI(pwd.value);
xmlHttp.open("GET",url,true);
xmlHttp.onreadyStatechange = show;
xmlHttp.send(null);
document.getElementById("message").innerHTML="正在登錄,請稍後..........";
}
}
function show()
{
if(xmlHttp.readyState == 4)//響應與完成,可以訪問服務器並響應它
{
if(xmlHttp.status == 200)//響應狀態一切順利
{
var xmlDOM = xmlHttp.responseText;
document.getElementById("message").innerHTML = xmlDOM;
}
}
}
</script>
<style type="text/css">
<!--
body
{
padding:1em 2em 3em 4em;
}
input
{
font-size:10px;
}
div
{
font-size:15px;
color:red;
}
-->
</style>
</head>
<body>
<center>
<div id="message"></div>
<table align="center" cellPadding="0" cellSpacing="1" bgcolor="blue" width="180">
<tr bgcolor="#ffffff">
<td>userName:</td><td><input type="text" id="userName" name="userName"/></td>
</tr>
<tr bgcolor="#ffffff">
<td>password:</td><td><input type="password" id="pwd" name="pwd"/></td>
</tr>
<tr bgcolor="#ffffff" align="center">
<td colspan="2"><input align="center" type="button" value="login" onclick="return login();"/></td>
</tr>
</table>
</center>
</body>
</html>
throws ServletException, IOException {
//注意這句代碼,設置服務器響應客戶端時的編碼格式,注意要寫GBK
response.setContentType("text/html;charset=GBK");
PrintWriter out = response.getWriter();
String userName=request.getParameter("userName");
String pwd = request.getParameter("pwd");
if(userName.equals("陳濤") && pwd.equals("chen")){
out.print("登錄成功");
}else{
out.print("登錄失敗");
}
out.flush();
out.close();
}
有興趣的朋友可以試一下,不管是請求處理亂碼還是響應信息亂碼都可以處理,如果在請求時還是出現亂碼問題,如果提交的是GET方法在servlet 的 doGet 方法中加入如下代碼,
userName = new String(userName.getBytes("iso-8859-1"),"gbk");jsp頁面不用改動;
有需要的朋友可在在此地址下載:http://d.download.csdn.net/down/383565/ctojxzsycztao