ajax连接数据库验证用户名存在问题
CheckServlet
-----------------------------------------
package servlets;
import java.io.*;
import java.sql.*;
import
java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServlet;
public class CheckServlet extends HttpServlet{
public static final String DBDRIVER="com.mysql.jdbc.Driver";
public static final String DBURL="jdbc:mysql://localhost:8889/username";
public static final String DBUSER="root";
public static final String DBPASS="root";
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws
ServletException,
IOException{
this.doPost(request, response);
}
public void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException{
request.setCharacterEncoding("gbk");
response.setContentType("text/html");
Connection conn=null;
PreparedStatement pstmt=null;
ResultSet rs=null;
PrintWriter out=response.getWriter();
String userid=request.getParameter("userid");//接受验证的用户名
out.println(userid);
try{
Class.forName(DBDRIVER);
conn=DriverManager.getConnection(DBURL,DBUSER,DBPASS);
String sql=" select * from name where username=?";
pstmt=conn.prepareStatement(sql);
pstmt.setString(1,userid);
rs=pstmt.executeQuery();
if(rs.next()){
if(rs.getString("username")==userid){
out.println("true");
}else{
out.println("false");
}
}
out.close();
}catch(Exception e){
e.printStackTrace();
}finally{
try{
conn.close();
}catch(
SQLException e){
e.printStackTrace();
}
}
}
}
----------------------------
check.jsp
<%@ page language="java" pageEncoding="utf-8"%>
<%@ page import="java.sql.*"%>
<%@ page import="java.util.*"%>
<!doctype html>
<html lang="en">
<body>
<script>
window.onload = initPage;
function initPage() {
document.getElementById("userid").onblur = checkUserid;//引用函数方法。
}
//创建请求对象
function createRequest() {
try {
request = new XMLHttpRequest();
} catch (tryMS) {
try {
request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (otherMS