js:
action:
dao:
html:
function checkLoginName() {
var loginName = document.myform.loginName.value;
if (loginName == "" || loginName == null) {
alert('用户名不能为空!');
return false;
} else {
var url = "action.do?method=checkLoginName&loginName=" + loginName;
send(url);
// document.myform.action = "action.do?method=checkLoginName";
// document.myform.submit();
}
}
var xmlHttp;
function createXmlHttp() {
if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xmlHttp = new ActiveXObject("MIcrosoft.XMLHttp");
}
}
function send(url) {
createXmlHttp();
xmlHttp.open("GET", url, true);
xmlHttp.onreadystatechange = processRequest;
xmlHttp.send(null);
}
function processRequest() {
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
var myfont = document.getElementById("name");
while (myfont.hasChildNodes()) {
myfont.removeChild(myfont.firstChild);
}
var text = document.createTextNode();
text.nodeValue = xmlHttp.responseText;
myfont.appendChild(text);
}
}
}
action:
public ActionForward checkLoginName(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
LoginDao dao=new LoginDao();
String loginName=request.getParameter("loginName");
loginName=new String(loginName.getBytes("ISO-8859-1"),"UTF-8");
System.out.println(loginName);
int num=dao.check(loginName);
if(num==0){
response.getWriter().println("可用");
response.getWriter().flush();
}else{
response.getWriter().println("已经使用");
response.getWriter().flush();
}
return null;
}
dao:
public int check(String loginName){
Session ss=HibernateSessionFactory.getSession();
ss.beginTransaction();
Query q=ss.createQuery("select loginName from Login where loginName='"+loginName+"'");
List list=q.list();
ss.getTransaction().commit();
ss.close();
return list.size();
}
html:
<tr>
<td width="100" align="right">
用户名:
</td>
<td align="left">
<input type="text" name="loginName" />  <input type="button" value="检查用户名" onclick="checkLoginName()">
<font color="red" size="2px" id="name"></font></td>
</tr>