【ajax】ajax異步實現用戶注冊驗證


從前台到后台實現簡單用戶注冊檢查用戶是否存在

1.編寫domain

public class User {
	private String username;
	private String password;
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
}

2.編寫dao

public class UserDao {
	/**
	 * 通過用戶名獲取用戶
	 * @param username
	 * @return
	 * @throws SQLException 
	 */
	public User getUserByUsername4Ajax(String username) throws SQLException {
		
		QueryRunner qr = new QueryRunner(DataSourceUtils.getDataSource());
		String sql = "select * from user where username = ? limit 1";
		User user = qr.query(sql, new BeanHandler<>(User.class), username);
		return user;
	}
}

3.編寫service

public class UserService {
	/**
	 * 檢測用戶名是否被占用
	 * @param username
	 * @return
	 * @throws SQLException
	 */
	public User checkUsername4Ajax(String username) throws SQLException{
		UserDao userDao = new UserDao();
		return userDao.getUserByUsername4Ajax(username);
	}
}

4.編寫controller

public class CheckUsername4AjaxServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 0.設置編碼
		
		// 1.接收用戶名
		String username = request.getParameter("username");
		username = new String(username.getBytes("iso-8859-1"),"utf-8");
		System.out.println(username);
		// 2.調用service 完成查詢 返回值user
		UserService userService = new UserService();
		User user = null;
		try {
			user = userService.checkUsername4Ajax(username);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		// 3.寫回信息
		if (user == null) {
			response.getWriter().println("1");
		} else {
			response.getWriter().println("0");
		}
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}

5.編寫注冊頁面

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    
    <title>用戶注冊</title>
	<script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery-1.11.3.min.js"></script>
  
  
  	<script type="text/javascript">
  	
  		$(function() {
  			// 給username派發一個失去焦點事件發送ajax請求
  			$("input[name='username']").blur(function() {
  				// 獲取輸入的文本內容
  				var $value = $(this).val();
  				var url = "${pageContext.request.contextPath}/checkUsername4Ajax";
  				var params = "username="+$value;
  				$.get(url, params, function(d) {
  					if (d == 1) {
						$("#username_msg").html("<font color='green'>用戶名可以使用</font>");
					} else {
						$("#username_msg").html("<font color='red'>用戶名已被占用</font>");
					}
  				});
  			});
  		
  		});
  	</script>
  </head>
  
  <body>
    <form action="" method="post" >
    	<table border="0" align="center" cellpadding="0">
    		<tr >
    			<td colspan="2" align="center"><h2>用戶注冊</h2></td>
    		</tr>
    		<tr>
    			<td>用戶名:</td>
    			<td><input type="text" name="username"/></td>
    			<td><span id="username_msg"></span></td>
    		</tr>
    		<tr>
    			<td>密碼:</td>
    			<td><input type="password" name="password"/></td>
    			<td></td>
    		</tr>
    		<tr>
    			<td colspan="3" align="center"><input type="submit" name="submit" id="submit" value="提交"/><input type="reset" name="reset" value="重置"/></td>
    		</tr>
    	</table>
    </form>
    
  </body>
</html>

附錄

1.DataSourceUtils工具類

public class DataSourceUtils {
	private static ComboPooledDataSource ds = new ComboPooledDataSource();
	
	private static ThreadLocal<Connection> tl = new ThreadLocal<>();
	
	/**
	 * 獲取數據源
	 * @return 連接池
	 */
	public static DataSource getDataSource() {
		return ds;
	}
	
	/**
	 * 從當前線程上獲取連接
	 * @return 連接
	 * @throws SQLException
	 */
	public static Connection getConnection() throws SQLException {
		Connection conn = tl.get();
		
		if (conn == null) {
			// 第一次獲取,創建一個連接和當前的線程綁定
			conn = ds.getConnection();
			
			// 綁定
			tl.set(conn);
		}
		return conn;
	}
	
	/**
	 * 釋放資源
	 * @param conn 連接
	 * @param st 語句執行者
	 * @param rs 結果集
	 */
	public static void closeResource(Connection conn, Statement st, ResultSet rs) {
		
		closeResource(st, rs);
		closeConn(conn);
	}

	/**
	 * 釋放連接
	 * @param conn 連接
	 */
	private static void closeConn(Connection conn) {
		if (conn != null) {
			try {
				conn.close();
				// 和當前的線程解綁
				tl.remove();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			conn = null;
		}
	}

	private static void closeResource(Statement st, ResultSet rs) {
		closeResultSet(rs);
		closeStatement(st);
	}

	private static void closeStatement(Statement st) {
		if (st != null) {
			try {
				st.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			st = null;
		}
		
	}

	private static void closeResultSet(ResultSet rs) {
		if (rs != null) {
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			rs = null;
		}
	}
	
	/**
	 * 開啟事務
	 * @throws SQLException
	 */
	public static void startTransaction() throws SQLException{
		// 獲取連接
		// 開始事務
		getConnection().setAutoCommit(false);
	}
	
	/**
	 * 事務提交
	 */
	public static void commitAndClose() {
		try {
			// 獲取連接
			Connection conn = getConnection();
			// 提交事務
			conn.commit();
			// 釋放資源
			conn.close();
			// 解除綁定
			tl.remove();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	public static void rollbackAndClose() {
		try {
			// 獲取連接
			Connection conn = getConnection();
			// 事務回滾
			conn.rollback();
			// 釋放資源
			conn.close();
			// 解除綁定
			tl.remove();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}

2.c3p0-config配置文件

<c3p0-config>
	<!-- 默認配置,如果沒有指定則使用這個配置 -->
	<default-config>
		<!-- 基本配置 -->
		<property name="driverClass">com.mysql.jdbc.Driver</property>
		<property name="jdbcUrl">jdbc:mysql://localhost:3306/ajax</property>
		<property name="user">root</property>
		<property name="password">123456</property>
	
		<!--擴展配置-->
		<property name="checkoutTimeout">30000</property>
		<property name="idleConnectionTestPeriod">30</property>
		<property name="initialPoolSize">10</property>
		<property name="maxIdleTime">30</property>
		<property name="maxPoolSize">100</property>
		<property name="minPoolSize">10</property>
		<property name="maxStatements">200</property>
	</default-config> 
</c3p0-config> 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM