<tr>
<th><span class="requiredField">*</span>用户名:</th>
<td><input type="text" id="username" name="username"
class="text" maxlength="20" οnblur="checkUsername()">
<span id="usernameSpan"></span>
</td>
</tr>
//AJAX用户名异步校验
function checkUsername(){
//获得文本框值:
var username = document.getElementById("username").value;
//1,创建异步交互对象
var xhr = createXmlHttp();
//2,设置监听
xhr.onreadystatechange = function(){
if(xhr.readyState == 4){
if(xhr.status == 200){
document.getElementById("usernameSpan").innerHTML = xhr.responseText;
}
}
}
//3,打开链接
xhr.open("GET","${pageContext.request.contextPath}/user_findByName.action?time="+new Date().getTime()+"&username="+username,true)
//4,发送
xhr.send(null);
}
function createXmlHttp(){
var xmlHttp;
try{
xmlHttp = new XMLHttpRequest();
}catch(e){
try{
xmlHttp = new ActiveXobject("Msxm12.XMLHTTP");
}catch(e){
try{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){}
}
}
return xmlHttp;
}
/**
* Ajax进行异步校验用户名的执行方法
*
* @throws IOException
*/
public String findByName() throws IOException {
// 调用Service进行查询:
User user = userService.findByUsername(model.getUsername());
// 获得response对象,向页面输出
HttpServletResponse response = ServletActionContext.getResponse();
// response.setCharacterEncoding("text/html;charset=UTF-8");//错误
response.setContentType("text/html;charset=UTF-8");
// 判断
if (user != null) {
// 查询到该用户:用户名已经存在
response.getWriter().println("<font color='red'>用户名已经存在</font>");
} else {
// 没查询到该用户:用户名可以使用
response.getWriter().println("<font color='green'>用户名可以使用</font>");
}
return NONE;
UserDao
public User findByUsername(String username) {
List<User> list = getSession().createQuery(//
"from User u where u.username = ?")//
.setParameter(0, username)//
.list();
if (list != null && list.size() > 0) {
return list.get(0);
}
return null;
}