1、构建数据库连接的工具类
package com.icss.DAO;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
/**
* 类的作用是加载驱动,建立连接,释放资源,增删改操作
* @author fly
*
*/
public class BaseDao {
//创建一个连接对象,返回connection
public static Connection getConnection(){
Connection connection = null;
//从连接池中取连接对象
Context cxtContext = null;
DataSource dsDataSource = null;
try {
cxtContext = new InitialContext();
dsDataSource = (DataSource)cxtContext.lookup("java:comp/env/myschoolConn");
connection = dsDataSource.getConnection();
} catch (Exception e) {
System.out.println("连接不成功");
}
return connection;
}
public static boolean executeUpdate(String sql,Object ...obj){
Connection connection = getConnection();
PreparedStatement pst = null;
int result = 0;
try {
pst = connection.prepareStatement(sql); //预编译
//判断是否有参数传入,如果没有,则obj数组是null
if(obj!=null){
for(int i =0;i<obj.length;i++){
pst.setObject(i+1, obj[i]);
}
}
result = pst.executeUpdate();
} catch (Exception e) {
System.out.println("数据库增删改有问题");
}finally{
closeAll(connection,pst,null);
}
return result>0;
}
public static void closeAll(Connection conn,Statement st,ResultSet rs){
try {
if(rs!= null) rs.close();
if(st!= null)st.close();
if(conn!=null) conn.close();
} catch (Exception e) {
System.out.println("关闭资源");
}
}
}
2、连接池的设置
在WebRoot下的META-INF中创建一个context.xml文件
<?xml version='1.0' encoding='utf-8'?>
<Context>
<Resource
name ="myschoolConn"
auth="Container"
type="javax.sql.DataSource"
maxActive="100"
maxIdle="30"
maxWait="10000"
username="root"
password="123456"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://127.0.0.1:3306/myschool?characterEncoding=utf-8"/>
</Context>
3、创建Ajaxl对象
package com.icss.entity;
public class Admin {
private int id;
private String loginId;
private String loginPwd;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getLoginId() {
return loginId;
}
public void setLoginId(String loginId) {
this.loginId = loginId;
}
public String getLoginPwd() {
return loginPwd;
}
public void setLoginPwd(String loginPwd) {
this.loginPwd = loginPwd;
}
}
4、创建dao层方法
package com.icss.DAO;
import com.icss.entity.Admin;
public interface AdminDao {
public Admin getAdminByLoginId(String loginId);
}
5、dao层方法的实现
package com.icss.Imp;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import com.icss.DAO.AdminDao;
import com.icss.DAO.BaseDao;
import com.icss.entity.Admin;
public class AdminDaoImp implements AdminDao {
@Override
public Admin getAdminByLoginId(String loginId) {
Connection connection = BaseDao.getConnection();
Statement statement = null;
ResultSet resultSet = null;
Admin admin = null;
String sqlString = "select * from admin where loginid = '"+loginId+"'";
try {
statement = connection.createStatement();
resultSet = statement.executeQuery(sqlString);
if(resultSet.next()){
admin = new Admin();
admin.setId(resultSet.getInt(1));
admin.setLoginId(resultSet.getString(2));
admin.setLoginPwd(resultSet.getString(3));
}
} catch (Exception e) {
}finally{
BaseDao.closeAll(connection, statement, resultSet);
}
return admin;
}
}
6、调用dao层方法
package com.icss.service;
import com.icss.DAO.AdminDao;
import com.icss.Imp.AdminDaoImp;
import com.icss.entity.Admin;
public class AdminService {
AdminDao dao = new AdminDaoImp();
public Admin getAdminByLoginId(String loginId){
return dao.getAdminByLoginId(loginId);
}
}
7、Servlet方法
package com.icss.Servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.icss.entity.Admin;
import com.icss.service.AdminService;
public class AdminServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String loginId = request.getParameter("loginId");
Admin admin = new AdminService().getAdminByLoginId(loginId);
if(admin == null){ //表示用户名不存在,则用户名可用
//向客户端返回信息
response.getWriter().write("yes");
}else{ //表示用户名不可用
response.getWriter().write("no");
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
8、采用JavaScript实现
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<style>
#div1{width:400px;margin:0 auto;}
</style>
<script type="text/javascript">
//1、获取XMLHttpRequest对象的函数
function getXMLHttpRequest(){
if(window.XMLHttpRequest){
return new XMLHttpRequest();
}
}
var xhr;
//文本框失去焦点触发函数
function inputLogin(txt){
xhr = getXMLHttpRequest(); //调用方法创建XMLHttpRequest对象
var loginId = txt.value; //取文本框的值
xhr.onreadystatechange=resultFunction; //设置回调函数
//初始化XMLHttpRequest对象
xhr.open("GET", "AdminServlet?loginId="+loginId,true);
//XMLHttpRequest对象发送请求
xhr.send(null);
}
//回调函数
function resultFunction(){
var s = document.getElementById("s");
if(xhr.readyState == 4){
if(xhr.status == 200){
var data = xhr.responseText;
if(data == "yes"){
s.style.color = "green";
s.innerHTML="用户名可用";
}else{
s.style.color = "red";
s.innerHTML="用户名已存在";
}
}
}
}
</script>
</head>
<body>
<div id="div1">
<h2>管理员添加</h2>
<from action="" method="post">
<fieldset>
<legend>注册信息</legend>
<p>用户名:<input type="text" name="loginId"onblur="inputLogin(this)" id="loginId"/><span id="s"></span></p>
<p>密 码:<input type="password" name="loginPwd"/></p>
<p><input type="submit" value="注册"></p>
</fieldset>
</from>
</div>
</body>
</html>
9、采用jquery实现
方法一:
<script type="text/javascript">
//文本框失去焦点触发函数
function inputLogin(txt){
var id = $("#loginId").val(); //取文本框值
var sp = $("#s"); //取span标签
$.ajax({
type:"GET",
url:"AdminServlet",
data:"loginId="+id,
dataType:"text",
success:function(d){
if(d == "yes"){
sp.css("color","green").html(" 用户名可用...");
}else{
sp.css("color","red").html(" 用户名已存在...");
}
}
});
}
</script>
方法二:
通过get方法
function inputLogin(txt){
var id = $("#loginId").val(); //取文本框值
var sp = $("#s"); //取span标签
$.get(
"AdminServlet",
{loginId:id},
function(d){
if(d == "yes"){
sp.css("color","green").html(" 用户名可用!");
}else{
sp.css("color","red").html(" 用户名已存在!");
}
},
"text"
);
}
也可以用post方法
function inputLogin(txt){
var id = $("#loginId").val(); //取文本框值
var sp = $("#s"); //取span标签
$.post(
"AdminServlet",
{loginId:id},
function(d){
if(d == "yes"){
sp.css("color","green").html(" 用户名可用!");
}else{
sp.css("color","red").html(" 用户名已存在!");
}
},
"text"
);
}