您的位置:首页 > 其它

案例分析-实现用户名唯一的验证操作

2014-04-30 11:13 603 查看
Admin.java

package www.csdn.net.ajax.domain;

import java.io.Serializable;

public class Admin implements Serializable {

/**
*
*/
private static final long serialVersionUID = 1L;
private Integer id;
private String name;
private String pass;
public Admin() {
super();
// TODO Auto-generated constructor stub
}
public Admin(Integer id, String name, String pass) {
super();
this.id = id;
this.name = name;
this.pass = pass;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPass() {
return pass;
}
public void setPass(String pass) {
this.pass = pass;
}
@Override
public String toString() {
return "Admin [id=" + id + ", name=" + name + ", pass=" + pass + "]";
}

}


BaseDao.java

package www.csdn.net.ajax.dao;

import java.util.List;

public interface BaseDao<T, PK> {

/**
* 插入实体
*
* @param entity
* @throws Exception
*/
void insert(T entity) throws Exception;

/**
* 更新实体
*
* @param entity
* @throws Exception
*/
void update(T entity) throws Exception;

/**
* 删除实体
*
* @param entity
* @throws Exception
*/
void delete(T entity) throws Exception;

/**
* 根据id删除实体
*
* @param id
* @throws Exception
*/
void deleteById(PK id) throws Exception;

/**
* 查询所有
*
* @return
* @throws Exception
*/
List<T> findAll() throws Exception;

/**
* 根据id查询实体对象
*
* @param id
* @return
* @throws Exception
*/
T findById(PK id) throws Exception;

/**
* 批量删除的操作
* @param ids
*/
void deletes(PK ids[])throws Exception;

/**
* 查询当前页信息
* @param nowpage
* @return
*/
List<T> findNowPageInfo(int nowpage)throws Exception;

Integer getCountPage()throws Exception;

}
AdminDao.java

package www.csdn.net.ajax.dao;

import www.csdn.net.ajax.domain.Admin;

public interface AdminDao extends BaseDao<Admin,Integer> {

/**
* 用户登录验证(根据用户名和密码)
* @param name
* @param pass
* @return
*/
Admin checkLogin(String name,String pass)throws Exception;

/**
* 判断用户名是否存在
* @param name
* @return
* @throws Exception
*/
boolean checkName(String name)throws Exception;

}


AdminDaoImpl.java

package www.csdn.net.ajax.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import www.csdn.net.ajax.dao.AdminDao;
import www.csdn.net.ajax.domain.Admin;
import www.csdn.net.ajax.util.DBConn;

public class AdminDaoImpl implements AdminDao {

private Connection conn;
private PreparedStatement pstmt;
private ResultSet rs;

@Override
public void insert(Admin entity) throws Exception {
String sql = "insert into admin(name,pass) values(?,?)";
DBConn.update(sql, new Object[] { entity.getName(), entity.getPass() });

}

@Override
public void update(Admin entity) throws Exception {
String sql = "update admin set name=?,pass=? where id=?";
DBConn.update(sql, new Object[] { entity.getName(), entity.getPass(),
entity.getId() });

}

@Override
public void delete(Admin entity) throws Exception {
String sql = "delete from admin where id=?";
DBConn.update(sql, new Object[] { entity.getId() });

}

@Override
public void deleteById(Integer id) throws Exception {
String sql = "delete from admin where id=?";
DBConn.update(sql, new Object[] { id });

}

@Override
public List<Admin> findAll() throws Exception {
List<Admin> entities = new ArrayList<Admin>();
String sql = "select id,name,pass from admin";
conn = DBConn.getConn();
pstmt = conn.prepareStatement(sql);
rs = pstmt.executeQuery();
while (rs.next()) {
Admin entity = new Admin();
entity.setId(rs.getInt("id"));
entity.setName(rs.getString("name"));
entity.setPass(rs.getString("pass"));
entities.add(entity);
}

return entities;
}

@Override
public Admin findById(Integer id) throws Exception {

Admin entity = null;
String sql = "select id,name,pass from admin where id=?";
conn = DBConn.getConn();
pstmt = conn.prepareStatement(sql);
int index = 1;
pstmt.setInt(index++, id);
rs = pstmt.executeQuery();
if (rs.next()) {
entity = new Admin();
entity.setId(rs.getInt("id"));
entity.setName(rs.getString("name"));
entity.setPass(rs.getString("pass"));
}

return entity;
}

@Override
public Admin checkLogin(String name, String pass) throws Exception {

Admin entity = null;
String sql = "select id,name,pass from admin where name=? and pass=?";
conn = DBConn.getConn();
pstmt = conn.prepareStatement(sql);
int index = 1;
pstmt.setString(index++, name);
pstmt.setString(index++, pass);
rs = pstmt.executeQuery();
if (rs.next()) {
entity = new Admin();
entity.setId(rs.getInt("id"));
entity.setName(rs.getString("name"));
entity.setPass(rs.getString("pass"));
}

return entity;
}

@Override
public void deletes(Integer[] ids) throws Exception {
conn = DBConn.getConn();
try {
for (int i = 0; i < ids.length; i++) {
String sql = "delete from admin where id=?";
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, ids[i]);
pstmt.executeUpdate();
}
conn.commit();
} catch (Exception e) {
conn.rollback();
e.printStackTrace();
}

}

final int PAGESIZE=10;
@Override
public List<Admin> findNowPageInfo(int nowpage)throws Exception {
List<Admin> entities = new ArrayList<Admin>();
String sql = "select id,name,pass from admin limit ?,?";

conn = DBConn.getConn();
pstmt = conn.prepareStatement(sql);

int index=1;
pstmt.setInt(index++, (nowpage-1)*PAGESIZE);
pstmt.setInt(index++, PAGESIZE);

rs = pstmt.executeQuery();
while (rs.next()) {
Admin entity = new Admin();
entity.setId(rs.getInt("id"));
entity.setName(rs.getString("name"));
entity.setPass(rs.getString("pass"));
entities.add(entity);
}

return entities;
}

@Override
public Integer getCountPage()throws Exception {

String sql = "select count(*) as c  from admin";

conn = DBConn.getConn();
pstmt = conn.prepareStatement(sql);

rs = pstmt.executeQuery();
if (rs.next()) {
int countsize=rs.getInt("c");
return countsize%PAGESIZE==0?countsize/PAGESIZE:countsize/PAGESIZE+1;
}

return null;
}

@Override
public boolean checkName(String name) throws Exception {
boolean  flag = false;
String sql = "select id,name,pass from admin where name=?";
conn = DBConn.getConn();
pstmt = conn.prepareStatement(sql);
int index = 1;
pstmt.setString(index++, name);
rs = pstmt.executeQuery();
if (rs.next()) {
flag=true;
}

return flag;
}

}
AdminServlet.java

package www.csdn.net.ajax.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 www.csdn.net.ajax.dao.AdminDao;
import www.csdn.net.ajax.dao.impl.AdminDaoImpl;

public class AdminServlet extends HttpServlet {

private AdminDao adminDao  = new AdminDaoImpl();

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

String oper = request.getParameter("oper");

if("checkName".equals(oper)){
//验证用户操作
checkName(request,response);
}
}

public void checkName(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

String name = request.getParameter("name");
boolean flag=false;
try {
flag = adminDao.checkName(name);
} catch (Exception e) {
e.printStackTrace();
}
//设置响应
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
if(flag){
out.write("用户名被占用");
}else{
out.write("用户名可以使用");
}
out.flush();
out.close();
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}

}


AjaxSerlet.java

package www.csdn.net.ajax.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AjaxServlet extends HttpServlet {

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

System.out.println("请求成功----------");

response.setContentType("text/html;charset=UTF-8");
response.getWriter().write("用户名已经存在");
}

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

}


DBConn.java

package www.csdn.net.ajax.util;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

public class DBConn {

private static Connection conn;

private DBConn() {

}

public static Connection getConn() {
try {
if (conn == null) {
// 创建集合对象
Properties properties = new Properties();
// 装载
properties.load(DBConn.class.getClassLoader()
.getResourceAsStream("db.properties"));
// 加载驱动程序
Class.forName(properties.getProperty("driverClassName"));
// 获取连接对象
conn = DriverManager.getConnection(
properties.getProperty("url"),
properties.getProperty("user"),
properties.getProperty("pass"));

conn.setAutoCommit(false);
}
} catch (Exception e) {
e.printStackTrace();
}

return conn;
}

//单个数据的增加 更新 删除 的事务处理
public static void update(String sql, Object params[]) {
PreparedStatement pstmt = null;
try {
pstmt = getConn().prepareStatement(sql);
for (int i = 0; i < params.length; i++) {
pstmt.setObject(i + 1, params[i]);
}
pstmt.executeUpdate();
conn.commit();
} catch (Exception e) {
try {
conn.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
e.printStackTrace();
} finally {
release(null, pstmt);
}

}

public static void release(ResultSet rs, PreparedStatement pstmt) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (pstmt != null) {
try {
pstmt.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}
}


WebRoot/login.jsp

<%@ 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%>">

<title>My JSP 'login.jsp' starting page</title>

<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<!-- 引入js文件 -->
<script type="text/javascript" src="./js/util.js"></script>
<script type="text/javascript" src="./js/login.js"></script>
</head>

<body>
<div align="center">
<form action="./login.action" method="post">
<table border="1px" cellpadding="0" cellspacing="0">
<tr>
<td>用户名:</td>
<td><input  type="text" name="name" id="uname"/></td>
<td><span id="msg"></span></td>
</tr>
<tr>
<td>密码:</td>
<td colspan="2"><input type="password" name="pass" /></td>
</tr>
<tr>
<td>验证码:</td>
<td><input type="text" name="code" /></td>
<td><img alt="验证码" src=""></td>
</tr>
<tr>
<td colspan="3" align="center"><input type="reset" value="重置" />
<input type="submit" value="登录" /></td>
</tr>
</table>
</form>

</div>
</body>
</html>


WebRoot/js/

login.js

//当窗体加载完毕后触发该函数
window.onload = function(){
//获取name输入框的Dom对象
var inputName = document.getElementById("uname");
//注册事件
inputName.onblur= checkName;
};

function checkName(){
var name = this.value;

//1.第一步获取XMLHttpRequest对象
var xmlHttp = getXMLHttp();
//2. 第二步:打开请求
xmlHttp.open("GET","./checkName.do?name="+name+"&oper=checkName");
//3.第三步:发送请求
xmlHttp.send(null);
//4.第四步:函数处理
xmlHttp.onreadystatechange= processProgram;

}

function processProgram(){
//判断是否处理完成,响应的是否正常
if(this.readyState==4&&this.status==200){
//服务器端响应过来的文本
var content = this.responseText;
//获取显示文本的span,Dom节点对象
var msgDom = document.getElementById("msg");
//清除操作
var childNodes =  msgDom.childNodes;
for(var i=0;i<childNodes.length;i++){
//删除所有的孩子节点
msgDom.removeChild(childNodes[i]);
}
//创建一个文本节点对象
var textDom =document.createTextNode(content);
//在显示文本的span,Dom节点中添加textDom的孩子节点
msgDom.appendChild(textDom);
}

}


util.js

function getXMLHttp() {
// 第一步:声明返回值
var xmlHttp;
// 第二步:实例化xmlHttp对象
try {
// firefox Opera等
xmlHttp = new XMLHttpRequest();
} catch (e) {
try {
// IE浏览器
xmlHttp = new ActiveXObject("MSXML2.XMLHTTP5.0");
} catch (ex) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐