欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Ajax验证用户名是否存在 博客分类: ajax ajaxservletJavaScript 

程序员文章站 2024-03-18 16:30:58
...

1.jsp代码

 

<%@ page language="java" contentType="text/html; charset=UTF-8"

pageEncoding="UTF-8"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>Insert title here</title>

<script type="text/javascript"

src="${pageContext.request.contextPath }/js/jquery-1.9.1.min.js"></script>

<script type="text/javascript">

$(function() {

$(":input[name='name']").change(function() {

var val = $(this).val();

val = $.trim(val);

 

if (val != "") {

var url = "${pageContext.request.contextPath}/userName";

var args = {

"name" : val,

"time" : new Date()

};

$.post(url, args, function(data) {

$("#sj").html(data);

 

})

 

}

 

})

 

})

</script>

</head>

<body>

<form action="" method="post">

name:<input type="text" name="name" /> <br> <br>

<div id="sj"></div>

<input type="submit" value="提交" />

 

</form>

</body>

</html>

 

2.servlet代码

 

 

package he.bdqn.ajax;

 

import java.io.IOException;

import java.util.Arrays;

import java.util.List;

 

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

 

/**

 * Servlet implementation class UserName

 */

@WebServlet("/userName")

public class UserName extends HttpServlet {

private static final long serialVersionUID = 1L;

 

/**

* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse

*      response)

*/

protected void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

List<String> names = Arrays.asList("aa", "bb", "cc");

 

String name = request.getParameter("name");

String result = null;

if (names.contains(name)) {

result = "<font color='red'>用户名被使用</font>";

} else {

result = "<font color='green'>用户名可以使用</font>";

}

 

response.setContentType("text/html");

response.setCharacterEncoding("utf-8");

response.getWriter().print(result);

}

 

}