首先先创建一张简单的表(略)
其次先封装了三个类,用来进行数据库的连接和事务的管理,代码如下
IRowMapper.java
package com.google.eshop.utils;
import java.sql.ResultSet;
/**
* ResultSet ->Object
* @author hanbin
*
* @param
*/
public interface IRowMapper {
public abstract T iRowMapper(ResultSet rs);
}
DBHelper.java
package com.google.eshop.utils;
import java.io.*;
import java.net.URLDecoder;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
public class DBHelper {
// 需要读取配置文件中的信息
private PreparedStatement psmd;
private Statement st;
private Connection conn;
private ResultSet rs;
private static Properties p;
// 执行更新个删除后 的标志位
private int rows = -1;
// 外部文件名
private static String configFile = "jdbc.properties";
// 数据库连接必须保持一个用户一个 ThreadLocal
private static InputStream in;
private ThreadLocal tl = new ThreadLocal();
static {
p = new Properties();
// 找到配置文件的路径
configFile = DBHelper.class.getClassLoader().getResource("").getPath() + configFile;
try {
configFile = URLDecoder.decode(configFile, "utf-8");
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println(configFile);
// 读取文件的信息 肯定IO操作
File file = new File(configFile);
try {
// 用流来读取文件信息
in = new BufferedInputStream(new FileInputStream(file));
// p.load将文件信息加载到Properties对象中
p.load(in);
Class.forName(p.getProperty("driver"));
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if(in!=null)
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 连接的方法 私有
*
* @return
*/
private void getConnection() {
// 从ThreadLocal取出连接
this.conn = tl.get();
if (conn == null) {
try {
conn = DriverManager.getConnection(p.getProperty("url"), p.getProperty("username"),
p.getProperty("password"));
} catch (SQLException e) {
e.printStackTrace();
}
}
// 放回ThreadLocal中
tl.set(conn);
}
/**
* 关闭的方法
*/
public void close() {
if (rs != null) {
try {
rs.close();
rs = null;
} catch (SQLException e) {
e.printStackTrace();
}
if (psmd != null) {
try {
psmd.close();
psmd = null;
} catch (SQLException e) {
e.printStackTrace();
}
}
try {
if (conn != null && !conn.isClosed()) {
conn.close();
conn = null;
// 将数据库连接移除
tl.remove();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 执行删除和更新的操作
*
* @param sql
* @param objs
* @return
* @throws SQLException
*/
public int executeUpdate(String sql, Object... objs) {
// 1.拿到数据库的连接
this.getConnection();
try {
psmd = conn.prepareStatement(sql);
// 必须封装一个设置参数的方法
this.setParams(objs);
rows = psmd.executeUpdate();
return rows;
} catch (SQLException e) {
e.printStackTrace();
}
return -1;
}
/**
* 设置参数的方法
*
* @param objs
*/
private void setParams(Object... objs) {
if (objs != null && objs.length > 0) {
for (int i = 0; i < objs.length; i++) {
try {
psmd.setObject(i + 1, objs[i]);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
/**
* 新增的方法
*
* @param sql
* @param objs
* @return
* @throws Exception
*/
public int executeSave(String sql, Object... objs) throws Exception {
this.getConnection();
try {
// 新增完成之后拿到自增的主键
psmd = conn.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS);
// 必须设置参数
this.setParams(objs);
rows = psmd.executeUpdate();
// 拿到自增的主键
rs = psmd.getGeneratedKeys();
while (rs.next()) {
// 返回自增主键
return rs.getInt(1);
}
} catch (SQLException e) {
e.printStackTrace();
}
return -1;
}
/**
* 查询的方法 IRowMapper是查询的结果 objs查询条件
*
* @param sql
* @param mapper
* @param objs
* @return
*/
public List executeQuery(String sql, IRowMapper mapper, Object... objs)throws Exception {
List tlist = new ArrayList();
this.getConnection();
try {
psmd = this.conn.prepareStatement(sql);
this.setParams(objs);
rs = psmd.executeQuery();
while (rs.next()) {
T t = mapper.iRowMapper(rs);
tlist.add(t);
}
} catch (SQLException e) {
e.printStackTrace();
}
return tlist;
}
/**
* 无参数的查询
*
* @param sql
* @param mapper
* @return
*/
public List executeQuery(String sql, IRowMapper mapper) {
List tlist = new ArrayList();
this.getConnection();
try {
st = this.conn.createStatement();
rs = st.executeQuery(sql);
while (rs.next()) {
T t = mapper.iRowMapper(rs);
tlist.add(t);
}
} catch (SQLException e) {
e.printStackTrace();
}
return tlist;
}
/**
* 执行聚合函数
*
* @param sql
* @param objs
* @return
*/
public Object executeScale(String sql, Object... objs) {
this.getConnection();
Object object = null;
try {
psmd = this.conn.prepareStatement(sql);
this.setParams(objs);
rs = psmd.executeQuery();
while (rs.next()) {
object = rs.getObject(1);
}
} catch (SQLException e) {
e.printStackTrace();
}
return object;
}
/**
* 开事务 将自动提交改为手动提交
*/
public void begins() {
try {
this.getConnection();
tl.get().setAutoCommit(false);
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 提交事务
*/
public void commit() {
try {
tl.get().commit();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void rollback() throws Exception {
try {
tl.get().rollback();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
BaseDao.java
package com.google.eshop.utils;
import org.apache.log4j.Logger;
/**
* 基础Dao
* @author ZhangYang
*
*/
public abstract class BaseDao {
private Logger LOG = Logger.getLogger(BaseDao.class);
protected DBHelper dbHelper = new DBHelper();
/**
* 开始事务
*/
public void begins () {
this.dbHelper.begins();
}
/**
* 提交事务
*/
public void commit() {
this.dbHelper.commit();
}
/**
* 回滚事务
*/
public void rollback() {
try {
this.dbHelper.rollback();
} catch (Exception e) {
LOG.error(e);
}
}
/**
* 关闭连接
*/
public void close() {
this.dbHelper.close();
}
}
下来会写Model User.java
package com.google.eshop.model;
public class User {
private int id;
private String username;
private String upassword;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getUpassword() {
return upassword;
}
public void setUpassword(String upassword) {
this.upassword = upassword;
}
}
其次是Dao层 (CRUD) UserDao.java
package com.google.eshop.dao;
import com.google.eshop.mapper.UserMapper;
import com.google.eshop.model.User;
import com.google.eshop.utils.BaseDao;
import org.apache.log4j.Logger;
import java.util.List;
public class UserDao extends BaseDao {
private Logger LOG=Logger.getLogger(UserDao.class);
public List queryUserByCond(String username,String upassword)throws Exception{
StringBuffer sql=new StringBuffer();
sql.append("select * from t_user where ");
sql.append("username=? and upassword=? ");
Listlist=null;
try {
list=this.dbHelper.executeQuery(sql.toString(),new UserMapper(),username,upassword);
} catch (Exception e) {
LOG.error(e);
throw new RuntimeException();
}
return list;
}
public List queryUserByName(String username) throws Exception{
List list = null;
StringBuffer sql = new StringBuffer();
sql.append("select * from t_user where username = ?");
try {
list = dbHelper.executeQuery( sql.toString(), new UserMapper(),username) ;
} catch (Exception e) {
LOG.error(e);
throw new RuntimeException();
}
return list;
}
}
下来是服务层 UserService.java
package com.google.eshop.service;
import com.google.eshop.dao.UserDao;
import com.google.eshop.model.User;
import org.apache.log4j.Logger;
import java.util.List;
//服务层
public class UserService {
//必须调用UserDao
private UserDao userDao=new UserDao();
private Logger LOG=Logger.getLogger(UserService.class);
public Listlogin(String username,String upassword) throws Exception{
Listlist=null;
try {
list=userDao.queryUserByCond(username,upassword);
} catch (Exception e) {
LOG.error(e);
throw new RuntimeException();
}finally{
this.userDao.close();
}
return list;
}
public List checkuserName(String username){
Listlist=null;
try {
list=userDao.queryUserByName(username);
} catch (Exception e) {
LOG.error(e);
throw new RuntimeException();
}finally{
this.userDao.close();
}
return list;
}
}
服务层的操作主要是调用Dao层和进行事务的管理 单表操作的话没有必要存在服务层
下来是控制层 CheckNameController.java
package com.google.eshop.servlet;
import com.alibaba.fastjson.JSON;
import com.google.eshop.model.User;
import com.google.eshop.service.UserService;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@WebServlet("/checkUserName")
public class CheckNameController extends HttpServlet {
private UserService userService=new UserService();
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//异步 不能跳转页面 当前页面
request.setCharacterEncoding("UTF-8");
String username=request.getParameter("username").trim();
Listlist=null;
try {
list=userService.checkuserName(username);
Map map=new HashMap();
if(list!=null&list.size()>0){
//状态传回页面
map.put("key","success");
}else{
map.put("key","failure");
}
//把Map对象转为JSON格式 键值对
String json=JSON.toJSONString(map);
System.out.println(json);
//将json写回页面
PrintWriter out = response.getWriter();
out.write(json);
} catch (Exception e) {
e.printStackTrace();
}
}
}
下来的是jsp页面 index.jsp
<%--
Created by IntelliJ IDEA.
User: 1270089912
Date: 2018/7/5
Time: 19:35
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
登录界面
${message}
user.js文件
$("#username").blur(function(){
var username=$("#username").val().trim();
if (username!=""){
//往服务器发请求
$.ajax({
type:"POST",//请求的方式默认为get 改为Post
url:"/checkUserName",//往服务器端请求的地址 写成绝对路径*/
data:{username:username},//往服务器端发送的数据*/
//接受服务器端数据函数 回调函数//
//接受服务器端数据函数 回调函数//
success:function (data) {
//data是服务器返回的数据
if (data!=""){
//后台传过来的数据需要转换
var json=JSON.parse(data);
if (json.key=="success"){
$("#userspan").html("用户名已存在");
}else{
$("#userspan").html("用户名可用");
}
}else{
$("#userspan").text("服务器端异常请稍后再试");
}
}
});
}
});
这样就实现了一个简单的异步操作 如果有读者有问题,欢迎留言,如看到会第一时间回复。
秋招的时间不多了,加油 !!!!