01.dao层查询数据库中数据返回数据提交给service层
02.service层调用dao层方法返回数据提交给controller层
03.controller层调用service层方法返回数据提交给view层
04.view层通过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>