AdminDao
package dao;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import entity.Admin;
public class AdminDao extends BaseDao {
/*
* 查询所有用户
*/
public List<Admin> getAllAdmins() {
List<Admin> adminList = new ArrayList<Admin>();
String sql = "select * from admins";
executeQuery(sql, null);
try {
while(rs.next()) {
adminList.add(new Admin(rs.getString("loginName"), rs.getString("loginPwd"), rs.getString("nickName")));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
closeAll();
}
return adminList;
}
/*
* 根据用户名和密码查询指定用户
*/
public Admin findAdminByNameAndPwd(String name, String pwd) {
String sql = "select * from admins where loginName = ? and loginPwd = ?";
Object[] params = { name, pwd };
executeQuery(sql, params);
try {
if (rs.next()) {
return new Admin(name, pwd, rs.getString("nickName"));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
closeAll();
}
return null;
}
/*
* 增加新用户
*/
public int addAdmin(Admin admin) {
String sql = "insert into admins values(?,?,?)";
Object[] params = { admin.getLoginName(), admin.getLoginPwd(),
admin.getNickName() };
return executeUpdate(sql, params);
}
/*
* 查询指定用户名是否存在
*/
public int findAdminNameCount(String name) {
String sql = "select count(*) from admins where loginName = ?";
Object[] params = { name };
executeQuery(sql, params);
try {
if (rs.next()) {
return rs.getInt(1);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
closeAll();
}
return 1;
}
}
BaseDao
package dao;
import java.sql.*;
public class BaseDao {
private static final String DRIVER = "oracle.jdbc.driver.OracleDriver";
private static final String URL = "jdbc:oracle:thin:@localhost:1521:orcl";
private static final String USER = "system";
private static final String PWD = "password";
protected Connection con;
protected PreparedStatement ps;
protected ResultSet rs;
protected void getConnection(){
try {
Class.forName(DRIVER);
con = DriverManager.getConnection(URL, USER, PWD);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
protected void closeAll(){
try {
if(null != rs) rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
if(null != ps) ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
if(null != con) con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
protected void executeQuery(String sql, Object[] params) {
getConnection();
try {
ps = con.prepareStatement(sql);
if(null != params) {
for (int i = 0; i < params.length; i++) {
ps.setObject(i+1, params[i]);
}
}
rs = ps.executeQuery();
} catch (SQLException e) {
e.printStackTrace();
}
}
protected int executeUpdate(String sql, Object[] params) {
getConnection();
try {
ps = con.prepareStatement(sql);
if(null != params) {
for (int i = 0; i < params.length; i++) {
ps.setObject(i+1, params[i]);
}
}
return ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
closeAll();
}
return -1;
}
}
Admin
package entity;
public class Admin {
private String loginName;
private String loginPwd;
private String nickName;
public Admin() {
}
public Admin(String loginName, String loginPwd, String nickName) {
super();
this.loginName = loginName;
this.loginPwd = loginPwd;
this.nickName = nickName;
}
public String getLoginName() {
return loginName;
}
public void setLoginName(String loginName) {
this.loginName = loginName;
}
public String getLoginPwd() {
return loginPwd;
}
public void setLoginPwd(String loginPwd) {
this.loginPwd = loginPwd;
}
public String getNickName() {
return nickName;
}
public void setNickName(String nickName) {
this.nickName = nickName;
}
}
AdminServlet
package servlet;
/*
* Servlet三大作用:1.获取表单数据2.处理业务逻辑3.分发转向
*/
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import dao.AdminDao;
import entity.Admin;
public class AdminServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String action = request.getParameter("action");
AdminDao ad = new AdminDao();
if("add".equals(action)) {
// 注册业务功能
Admin admin = new Admin(request.getParameter("rname"), request.getParameter("rpwd"), request.getParameter("rnickname"));
if(ad.addAdmin(admin) > 0 ){
// 成功
out.print("true");//这个字符串返回到给demo.jsp里面的result,然后进行判断
} else {
// 失败
out.print("false");
}
} else if("login".equals(action)) {
// 登录业务功能
String name = request.getParameter("lname");
String pwd = request.getParameter("lpwd");
Admin admin = ad.findAdminByNameAndPwd(name, pwd);
if(null == admin) {
// 登录失败
out.print("{\"flag\":\"false\"}");
} else {
// 登陆成功
out.print("{\"flag\":\"true\",\"nickName\":\""+admin.getNickName()+"\"}");
}
} else if("queryAll".equals(action)) {
List<Admin> adminList = ad.getAllAdmins();
StringBuffer resultBuf = new StringBuffer("[");
for (Admin admin : adminList) {
resultBuf.append("{\"name\":\""+admin.getLoginName()+"\",\"pwd\":\""+admin.getLoginPwd()+"\",\"nickName\":\""+admin.getNickName()+"\"},");
}
String result = resultBuf.toString();
result = result.substring(0, result.length()-1);
result += "]";
System.out.print(result);
out.print(result);
}
out.flush();
out.close();
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
demo
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Ajax交互</title>
<script type="text/javascript" src="js/jquery-1.8.3.min.js"></script>
<script type="text/javascript">
$(function(){
$("input[value=注册]").click(function(){
var name = $("input[name=regName]").val();
var pwd = $("input[name=regPwd]").val();
var nickName = $("input[name=regNickName]").val();
// 使用jQueryAjax实现注册功能
$.ajax({
url:"AdminServlet",
type:"post",
data:{"rname":name,"rpwd":pwd,"rnickname":nickName,"action":"add"},
dataType:"text",//注意类型,注册是文本类型
success:function(result) {
if("true"==result){
var $msg = $("<span>注册成功!</span>");
$("input[value=注册]").after($msg);
} else {
var $msg = $("<span>注册失败!</span>");
$("input[value=注册]").after($msg);
}
}
});
});
$("input[value=登录]").click(function(){
var name = $("input[name=loginName]").val();
var pwd = $("input[name=loginPwd]").val();
$.ajax({
url:"AdminServlet",
type:"post",
data:{"lname":name,"lpwd":pwd,"action":"login"},
dataType:"JSON",//登录是JSON类型
success:function(result){
var show = "登陆失败!";
if(result.flag == "true"){
show = "登录成功!你好:"+result.nickName+"!";
}
$msg = $("<span>"+show+"</span>");
$("input[value=登录]").after($msg);
}
});
});
$("input[value=显示所有用户]").click(function(){
$.ajax({
url:"AdminServlet",
type:"post",
data:{"action":"queryAll"},
dataType:"JSON",
success:function(result){
var showUL = "<ul>";
$.each(result,function(){
var li = "<li>用户名:"+this.name+",密码:"+this.pwd+",昵称"+this.nickName+"</li>";
showUL += li;
});
showUL+="</ul>";
var $show = $("<br />"+showUL);
$("input[value=显示所有用户]").after($show);
}
});
});
});
</script>
</head>
<body>
用户名:<input type="text" name="regName" /> <br />
密码:<input type="password" name="regPwd" /> <br />
昵称:<input type="text" name="regNickName" /> <br />
<input type="button" value="注册" /> <br />
<hr />
登录用户名:<input type="text" name="loginName" /> <br />
登录密码:<input type="password" name="loginPwd" /> <br />
<input type="button" value="登录" /> <br />
<hr />
<input type="button" value="显示所有用户" /> <br />
<hr />
</body>
</html>