我正在尝试按照本教程创建简单的唯一用户名检查。
http://javaandj2eetutor.blogspot.com/2013/12/check-username-availability-using-java.html
但我对用户名的ajax调用失败了。我是ajax的新手,对于jsp来说有点新鲜。
这是我的index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Username Availability</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(document).ready(function () {
$(".username").change(function () {
var username = $(this).val();
if (username.length >= 3) {
$(".status").html("<font color=gray> Checking availability...</font>");
$.ajax({
type: "POST",
url: "CheckAvalability",
data: "uname="+ username,
success: function (msg) {
$(".status").ajaxComplete(function (event, request, settings) {
$(".status").html(msg);
});
}
});
}
else {
$(".status").html("<font color=red>Username should be <b>3</b> character long.</font>");
}
});
});
</script>
<div>
<label class="flable">User Name :</label> <input class="username" type="text" name="username"> <span class="status"></span>
</div>
</body>
</html>
这是我的Servlet
package hsenid;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.*;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;
public class CheckAvailability extends HttpServlet {
private static final Logger logger = LogManager.getLogger(CheckAvailability.class);
private static final long serialVersionUID = -734503860925086969L;
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
logger.info("Check availability called");
DBConnector dbPool = (DBConnector)getServletContext().getAttribute("DBConnection");
Connection myConn = dbPool.getConn();
String uname = request.getParameter("username");
PreparedStatement ps = myConn.prepareStatement("select username from userdetails where username=?");
ps.setString(1,uname);
ResultSet rs = ps.executeQuery();
if (!rs.next()) {
out.println("<font color=green><b>"+uname+"</b> is avaliable</font>");
logger.info("Username detected!!!");
}
else{
out.println("<font color=red><b>"+uname+"</b> is already in use</font>");
}
out.println();
} catch (Exception ex) {
out.println("Error ->" + ex.getMessage());
} finally {
out.close();
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
}
这是我在web.xml中的servlet映射。
<servlet>
<servlet-name>CheckAvailability</servlet-name>
<servlet-class>hsenid.CheckAvailability</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CheckAvailability</servlet-name>
<url-pattern>/CheckAvailability</url-pattern>
</servlet-mapping>
这会检测是否添加了最小字符,并在输入时提供按摩检查可用性,因此我认为添加了jquery。我也在Eclipse Mars中运行servlet。它会检查用户名是否在表中。所以我认为调用servlet的问题是因为我无法看到log4j控制台输出。我无法找到我的代码有什么问题。 提前致谢