1,目录及效果图
2,登录界面
<%@page contentType="text/html;charset=utf-8"%>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登入系统</title>
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/css/style.css" />
</head>
<body>
<div id="wrap">
<div id="top_content">
<div id="topheader">
<h1 id="title">
<a href="#">我爱登陆HPE</a>
</h1>
</div>
<div id="navigation"></div>
<div id="content">
<p id="whereami"></p>
<h1>登入系统</h1>
<p> </p>
<form action="${pageContext.request.contextPath}/SLogin" method="post">
<table class="form_table">
<tr>
<td>用户名:</td>
<td>
<input type="text" name="username" class="inputgri" value="" />
</td>
</tr>
<tr>
<td>密码:</td>
<td>
<input type="password" name="pwd" class="inputgri" />
</td>
</tr>
</table>
<p>
<input type="submit" class="button" value="提交 »" /> <a
href="${pageContext.request.contextPath}/register.jsp">注册新用户</a>
</p>
<p>
</p>
</form>
</div>
</div>
<div id="footer">
<div id="footer_bg">[email protected]</div>
</div>
</div>
</body>
<script type="text/javascript">
// 获取url中参数
var flag = ${param.flag};
if(flag == 1){
alert("登录失败,请重新登录!");
}
if(flag == 2){
alert("注册成功,请点击登录。");
}
</script>
</html>
3,注册界面
<%@page contentType="text/html;charset=utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
// http :// localhost:8080/v1_LoginDemo_servlet
%>
<!DOCTYPE html>
<html lang="en">
<head>
<title>注册用户</title>
<meta charset="UTF-8">
<base href="<%=basePath %>">
<link rel="stylesheet" type="text/css" href="css/style.css" />
<script type="text/javascript" src="js/calendar.js"></script>
<link type="text/css" rel="stylesheet" href="css/calendar-blue.css"></link>
</head>
<body>
<div id="wrap">
<div id="top_content">
<div id="header">
<div id="rightheader">
<p>
<span>${currentTime}</span>
<span><a href="${pageContext.request.contextPath}/index.jsp">退出</a></span><br />
</p>
</div>
<div id="topheader">
<h1 id="title">
<a href="#">我爱登陆</a>
</h1>
</div>
<div id="navigation"></div>
</div>
<div id="content">
<p id="whereami">
</p>
<h1>
注册新用户
</h1>
<p>
</p>
<form action="${pageContext.request.contextPath}/SRegister" method="post" >
<table>
<tr>
<td>用户名:</td>
<td><input type="text" name="username" value=""></td>
</tr>
<tr>
<td>密码:</td>
<td><input type="password" name="pwd"></td>
</tr>
<tr>
<td>确认密码:</td>
<td><input type="password" name="pwd1"></td>
</tr>
<tr>
<td>性别:</td>
<td>
<input type="radio" name="sex" value="1">男
<input type="radio" name="sex" value="0">女
<span id="sex_span"></span>
</td>
</tr>
<tr>
<td>个人爱好:</td>
<td>
<input type="checkbox" name="love" value="文学">文学
<input type="checkbox" name="love" value="影视">影视
<input type="checkbox" name="love" value="音乐">音乐
<input type="checkbox" name="love" value="体育">体育
</td>
</tr>
<tr>
<td>出生日期:</td>
<td>
<input type="text" id="birthday" name="birthday" >
</td>
</tr>
<tr>
<td>地址:</td>
<td><input type="text" name="address" value=""></td>
</tr>
<tr>
<td>邮箱:</td>
<td><input type="text" name="email" value=""></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" name="update" value="提交" class="button">
<input type="reset" name="reset" value="重置" class="button">
</td>
</tr>
</table>
</form>
</div>
</div>
<div id="footer">
<div id="footer_bg">[email protected]</div>
</div>
</div>
</body>
<script type="text/javascript">
Calendar.setup({
inputField : "birthday",
ifFormat : "%Y-%m-%d",
showsTime : true,
timeFormat : "24"
});
</script>
</html>
4,修改界面
<%@page contentType="text/html;charset=utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
// http :// localhost:8080/v1_LoginDemo_servlet
%>
<!DOCTYPE html>
<html lang="en">
<head>
<title>修改用户</title>
<meta charset="UTF-8">
<base href="<%=basePath %>">
<link rel="stylesheet" type="text/css" href="css/style.css" />
<script type="text/javascript" src="js/calendar.js"></script>
<link type="text/css" rel="stylesheet" href="css/calendar-blue.css"></link>
</head>
<body>
<div id="wrap">
<div id="top_content">
<div id="header">
<div id="rightheader">
<p>
<span>${currentTime}</span>
<span><a href="${pageContext.request.contextPath}/index.jsp">退出</a></span><br />
</p>
</div>
<div id="topheader">
<h1 id="title">
<a href="#">我爱登陆</a>
</h1>
</div>
<div id="navigation"></div>
</div>
<div id="content">
<p id="whereami">
</p>
<h1>
注册新用户
</h1>
<p>
</p>
<form action="${pageContext.request.contextPath}/Ssave" method="post" >
<input type="hidden" name="username" value="${user.getUsername()}">
<table>
<tr>
<td>密码:</td>
<td><input type="password" name="pwd" value="${user.getPwd()}"></td>
</tr>
<tr>
<td>确认密码:</td>
<td><input type="password" name="pwd1"></td>
</tr>
<tr>
<td>性别:</td>
<td>
<input type="radio" name="sex" value="1" ${1 eq user.getSex()?"checked":""}>男
<input type="radio" name="sex" value="0" ${0 eq user.getSex()?"checked":""}>女
<span id="sex_span"></span>
</td>
</tr>
<tr>
<td>个人爱好:</td>
<td>
<input type="checkbox" name="love" value="文学" ${fn:contains(user.getLove(),'文学')?"checked":""} >文学
<input type="checkbox" name="love" value="影视" ${fn:contains(user.getLove(),'影视')?"checked":""} >影视
<input type="checkbox" name="love" value="音乐" ${fn:contains(user.getLove(),'音乐')?"checked":""} >音乐
<input type="checkbox" name="love" value="体育" ${fn:contains(user.getLove(),'体育')?"checked":""} >体育
</td>
</tr>
<tr>
<td>出生日期:</td>
<td>
<input type="text" id="birthday" name="birthday" value="${user.getBirthday()}">
</td>
</tr>
<tr>
<td>地址:</td>
<td><input type="text" name="address" value="${user.getAddress()}"></td>
</tr>
<tr>
<td>邮箱:</td>
<td><input type="text" name="email" value="${user.getEmail()}"></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" name="update" value="提交" class="button">
<input type="reset" name="reset" value="重置" class="button">
</td>
</tr>
</table>
</form>
</div>
</div>
<div id="footer">
<div id="footer_bg">[email protected]</div>
</div>
</div>
</body>
<script type="text/javascript">
Calendar.setup({
inputField : "birthday",
ifFormat : "%Y-%m-%d",
showsTime : true,
timeFormat : "24"
});
</script>
</html>
5,主界面
<%@page import="java.util.ArrayList,com.hpe.bean.*"%>
<%@page contentType="text/html;charset=utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<!-- 权限判断 -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>用户列表</title>
<link rel="stylesheet" type="text/css"
href="${pageContext.request.contextPath}/css/style.css" />
<script src="${pageContext.request.contextPath}/js/jquery-3.1.1.min.js"></script>
<style type="text/css">
label {
margin: 5px;
font-size: 1.0em;
}
</style>
</head>
<body>
<div id="wrap">
<div id="top_content">
<div id="header">
<div id="rightheader">
<p>
<span>${currentTime}</span>
<span><a href="${pageContext.request.contextPath}/index.jsp">退出</a></span><br />
</p>
</div>
<div id="topheader">
<h1 id="title">
<a href="#">我爱登录</a>
</h1>
</div>
<div id="navigation">
<ul>
<li><a>首页</a></li>
<li><a>新闻</a></li>
<li><a>作品</a></li>
</ul>
</div>
</div>
<div id="content">
<p id="whereami"></p>
<h1>用户列表</h1>
<form action="UserOpera" method="post">
<label>用户名</label><input type="text" name="username">
<label>性别</label><input type="text" name="sex">
<input type="submit" name="sel" value="查询">
</form>
<br><br>
<table class="table">
<tr class="table_header">
<td>编号</td>
<td>用户名</td>
<td>密码</td>
<td>性别</td>
<td>爱好</td>
<td>地址</td>
<td>邮编</td>
<td>创建时间</td>
<td>操作</td>
</tr>
<c:forEach items="${list}" var="user" step="1">
<tr>
<td>${user.getId()}</td>
<td>${user.getUsername()}</td>
<td>${user.getPwd()}</td>
<td>${user.getSex()}</td>
<td>${user.getLove()}</td>
<td>${user.getAddress()}</td>
<td>${user.getEmail()}</td>
<td>${user.getCreateDate()}</td>
<td><a href="${pageContext.request.contextPath}/UserOpera?opea=add">增加</a>
<a href="${pageContext.request.contextPath}/UserOpera?name=${user.getUsername()}&opea=del">删除</a>
<a href="${pageContext.request.contextPath}/UserOpera?name=${user.getUsername()}&opea=modi">修改</a>
</td>
</tr>
</c:forEach>
</table>
</div>
</div>
<div id="footer">
<div id="footer_bg">[email protected]</div>
</div>
</div>
</body>
</html>
6,错误跳转界面
<%@ page language="java" import="java.util.*"
pageEncoding="utf-8"%>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<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">
<style type="text/css">
.error{
text-align: center;
}
span{
color: red;
}
</style>
</head>
<body>
<div class="error">
<span>${msg}</span><br>
<strong>请重新登录!!</strong><br>
</div>
</body>
</html>
7,servlet层
7.1. SLogin.java
package com.hpe.servlet;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
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 com.hpe.bean.User;
import com.hpe.service.Login;
/**
* Servlet implementation class Login
*/
@WebServlet("/SLogin")
public class SLogin extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
String username = request.getParameter("username");
String pwd = request.getParameter("pwd");
//封装数据
User user=new User(username, pwd);
//获取web应用路径
String contextPath = request.getContextPath();
//service层注入,业务处理
Login login=new Login();
int flag = login.login(user);
if (flag==0) {
// request.setAttribute("msg", "密码错误");
// request.getRequestDispatcher("error.jsp").forward(request, response);
//response.sendRedirect(contextPath+"/error.jsp");
response.sendRedirect(contextPath+"/index.jsp?flag=1");
}else if (flag==-1) {
// request.setAttribute("msg", "用户名不存在");
// request.getRequestDispatcher("error.jsp").forward(request, response);
//response.sendRedirect(contextPath+"/error.jsp");
response.sendRedirect(contextPath+"/index.jsp?flag=1");
}else {
//response.sendRedirect(contextPath+"/user/list.jsp");
Date date=new Date();
SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd");
//创建时间
String currentTime=sf.format(date);
request.getSession().setAttribute("currentTime",currentTime );
request.getSession().setAttribute("UserName",username );
request.getRequestDispatcher("SList").forward(request, response);
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
7.2. SRegister.java
package com.hpe.servlet;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.Enumeration;
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 com.hpe.bean.User;
import com.hpe.service.Register;
/**
* Servlet implementation class SRegister
*/
@WebServlet("/SRegister")
public class SRegister extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
String username = request.getParameter("username");
String pwd = request.getParameter("pwd");
String sex = request.getParameter("sex");
//拼接字符串
String[] loves=request.getParameterValues("love");
String love=loves[0];
for (int i = 1;loves!=null && i < loves.length; i++) {
love+=","+loves[i];
}
String birthday = request.getParameter("birthday");
String address = request.getParameter("address");
String email = request.getParameter("email");
Date date=new Date();
SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//创建时间
String createDate=sf.format(date);
//修改时间 默认第一次修改时间是创建时间
String updateDate=createDate;
User user=new User(username, pwd, sex, love, birthday, address, email, createDate, updateDate);
//service注入
Register register=new Register();
boolean flag = register.register(user);
//获取web应用路径
String contextPath = request.getContextPath();
if (flag) {
response.sendRedirect(contextPath+"/index.jsp");
}else {
response.sendRedirect(contextPath+"/register.jsp?flag=1");
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
7.3. SList.java
package com.hpe.servlet;
import java.io.IOException;
import java.util.List;
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 com.hpe.service.UserOperate;
/**
* Servlet implementation class SList
*/
@WebServlet("/SList")
public class SList extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
UserOperate userList=new UserOperate();
List list = userList.list();
//获取web应用路径
String contextPath = request.getContextPath();
request.setAttribute("list", list);
request.getRequestDispatcher("user/list.jsp").forward(request, response);
//response.sendRedirect(contextPath+"/user/list.jsp?list="+list);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
7.4. SUserOpera
package com.hpe.servlet;
import java.io.IOException;
import java.util.List;
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 com.hpe.bean.User;
import com.hpe.service.UserOperate;
/**
* Servlet implementation class UserOpera
*/
@WebServlet("/UserOpera")
public class SUserOpera extends HttpServlet {
private static final long serialVersionUID = 1L;
//service层注入
UserOperate userOperate=new UserOperate();
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
String username = request.getParameter("name");
String opea=request.getParameter("opea");
//获取web应用路径
String contextPath = request.getContextPath();
if (opea.equals("del")) {
int del = userOperate.del(username);
if (del==1) {
request.getRequestDispatcher("/SList").forward(request, response);
}
if (del==-1) {
request.setAttribute("msg", "要删除的用户不存在");
request.getRequestDispatcher("error.jsp").forward(request, response);
}
if (del==0) {
request.setAttribute("msg", "删除失败");
request.getRequestDispatcher("error.jsp").forward(request, response);
}
}
if(opea.equals("add")) {
response.sendRedirect(contextPath+"/register.jsp");
}
if(opea.equals("modi")) {
User select = userOperate.select(username);
request.setAttribute("user", select);
request.getRequestDispatcher("modi.jsp").forward(request, response);
}
}
/*
* 混合查询
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//post提交方式 用于查询表单的处理
request.setCharacterEncoding("utf-8");
String username = request.getParameter("username");
String sex=request.getParameter("sex");
List selectByName = userOperate.SelectByName(username, sex);
request.setAttribute("list", selectByName);
request.getRequestDispatcher("user/list.jsp").forward(request, response);
}
}
7.5. Ssave.java用于更新后的保存
package com.hpe.servlet;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
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 com.hpe.bean.User;
import com.hpe.service.UserOperate;
/**
* Servlet implementation class Ssave
*/
@WebServlet("/Ssave")
public class Ssave extends HttpServlet {
private static final long serialVersionUID = 1L;
UserOperate userOperate=new UserOperate();
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
String username = request.getParameter("username");
String pwd = request.getParameter("pwd");
String sex = request.getParameter("sex");
//拼接字符串
String[] loves=request.getParameterValues("love");
String love=loves[0];
for (int i = 1;loves!=null && i < loves.length; i++) {
love+=","+loves[i];
}
String birthday = request.getParameter("birthday");
String address = request.getParameter("address");
String email = request.getParameter("email");
Date date=new Date();
SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//修改时间 默认第一次修改时间是创建时间
String updateDate=sf.format(date);
User user=new User(username, pwd, sex, love, birthday, address, email, updateDate);
int flag = userOperate.modify(user);
if (flag==1) {
request.getRequestDispatcher("/SList").forward(request, response);
}
if (flag==-1){
request.setAttribute("msg", "要修改的用户不存在");
request.getRequestDispatcher("error.jsp").forward(request, response);
}
if (flag==0) {
request.setAttribute("msg", "修改失败");
request.getRequestDispatcher("error.jsp").forward(request, response);
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
8,service层
8.1. Login.java
package com.hpe.service;
import com.hpe.base.BaseDao;
import com.hpe.bean.User;
public class Login {
//dao层注入
BaseDao<User> baseDao=new BaseDao<>();
public int login(User u) {
String sql="select * from t_user where userName=?";
Object[] params= {u.getUsername()};
User user = baseDao.get(sql, User.class, params);
if (user==null) {
//用户名不存在
return -1;
}else {
if (u.getPwd().equals(user.getPwd())) {
//登陆成功
return 1;
}else {
//密码错误
return 0;
}
}
}
}
8.2.Register.java
package com.hpe.service;
import com.hpe.base.BaseDao;
import com.hpe.bean.User;
public class Register {
//dao层注入
BaseDao<User> baseDao=new BaseDao<>();
public boolean register(User u) {
String sql="insert into t_user(username,pwd,sex,love,birthday,address,email,createDate,updateDate) values(?,?,?,?,?,?,?,?,?)";
boolean flag=false;
Object[] params= {u.getUsername(),
u.getPwd(),
u.getSex(),
u.getLove(),
u.getBirthday(),
u.getAddress(),
u.getEmail(),
u.getCreateDate(),
u.getUpdateDate()
};
try {
boolean update = baseDao.update(sql, params);
if (update) {
flag=true;
}else {
flag=false;
}
} catch (Exception e) {
e.printStackTrace();
}
return flag;
}
}
8.3. UserOperate.java
package com.hpe.service;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.hpe.base.BaseDao;
import com.hpe.bean.User;
public class UserOperate {
//dao层注入
BaseDao<User> baseDao=new BaseDao<>();
/*
* 获取list用户列表
*/
public List list() {
String sql="select * from t_user";
Object[] params={};
List<User> query = baseDao.query(sql, User.class, params);
return query;
}
/*
* 混合查询
*/
public List SelectByName(String username,String sex) {
StringBuilder sql = new StringBuilder("select * from t_user where 1=1");
if (username.length()>0&&sex.length()>0) {
sql.append(" and username=? and sex=?");
Object[] params= {username,sex};
return baseDao.query(sql+"", User.class, params);
}else if(username.length()>0){
sql.append(" and username=?");//注意空格
Object[] params= {username};
return baseDao.query(sql+"", User.class, params);
}else if(sex.length()>0){
sql.append(" and sex=?");//注意空格
Object[] params= {sex};
return baseDao.query(sql+"", User.class, params);
}else {
sql.append("");
Object[] params= {};
return baseDao.query(sql+"", User.class, params);
}
}
/*
* 根据姓名删除
*/
public int del(String username) {
String sql1="select * from t_user where username=?";
String sql="delete from t_user where username=?";
Object[] params= {username};
int flag=0;
User user = baseDao.get(sql1, User.class, params);
if (user==null) {
//要删除的用户不存在
flag=-1;
}else {
try {
boolean update = baseDao.update(sql, params);
if (update) {
//删除成功
flag=1;
}else {
//删除失败
flag=0;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return flag;
}
/*
* 根据姓名单查询
*/
public User select(String username) {
String sql="select * from t_user where username=?";
Object[] params= {username};
return baseDao.get(sql, User.class, params);
}
/*
* 修改用户信息
*/
public int modify(User u) {
String sql1="select * from t_user where username=?";
String sql="update t_user set pwd=?,sex=?,love=?,birthday=?,address=?,email=?,updateDate=? where username=?";
Date date=new Date();
SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String updateDate=sf.format(date);
Object[] params1= {u.getUsername()};
Object[] params= {u.getPwd(),
u.getSex(),
u.getLove(),
u.getBirthday(),
u.getAddress(),
u.getEmail(),
u.getUpdateDate(),
u.getUsername()};
int flag=0;
User user = baseDao.get(sql1, User.class, params1);
if (user==null) {
//要修改的用户不存在
flag=-1;
}else {
try {
boolean update = baseDao.update(sql, params);
if (update) {
//修改成功
flag=1;
}else {
//修改失败
flag=0;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return flag;
}
}
9,base层(Dao层)
package com.hpe.base;
import java.sql.*;
import java.util.List;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import com.hpe.util.MyDataSource;
/**
* dao层公共方法类。
* 增删改方法 ,默认支持事务,需要在业务类中,添加事务。
* @author yaohuicheng
*
* @param <T>
*/
public class BaseDao<T>{
private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>();
/**
* 返回单个对象
* @param <T>
*
* @param sql
* @param clazz
* @param params
* 如果没有参数就设为 Object[] params={}
* @return
*/
public <T> T get(String sql, Class<T> clazz, Object[] params) {
T obj = null;
Connection conn = null;
try {
conn = MyDataSource.getConnection();
QueryRunner qRunner = new QueryRunner();
obj = qRunner.query(conn, sql, new BeanHandler<T>(clazz), params);
} catch (SQLException e) {
e.printStackTrace();
} finally {
DbUtils.closeQuietly(conn);
}
return obj;
}
/**
* 返回多个对象
*
* @param sql
* @param clazz
* @param params
* 如果没有参数就设为 Object[] params={}
* @return
*/
public <T> List<T> query(String sql, Class<T> clazz, Object[] params) {
List beans = null;
Connection conn = null;
try {
conn = MyDataSource.getConnection();
QueryRunner qRunner = new QueryRunner();
beans = (List) qRunner.query(conn, sql, new BeanListHandler<T>(clazz), params);
} catch (SQLException e) {
e.printStackTrace();
} finally {
DbUtils.closeQuietly(conn);
}
return beans;
}
/**
* 返回增删改是否成功
* 【注意,此方法没有关闭connection连接;需要在事务中关闭。 】
* @param sql
* @param params
* @return
* @throws Exception
*/
public boolean update(String sql, Object[] params) throws Exception {
Connection conn = getConnection();
boolean flag = false;
QueryRunner qRunner = new QueryRunner();
int i = qRunner.update(conn, sql, params);
if (i > 0) {
flag = true;
}
return flag;
}
/***
* 批量操作,需要用到事务
* 【注意,此方法没有关闭connection连接;需要在事务中关闭。 】
* @param conn
* @param sql
* @param params
* @return
* @throws Exception
*/
public boolean batchUpdate(String sql, Object[][] params) throws Exception {
QueryRunner qRunner = new QueryRunner();
int result = 0;
boolean flag = false;
result = qRunner.batch(getConnection(), sql, params).length;
if (result > 0) {
flag = true;
}
return flag;
}
/**
* 返回统计单值,
* @param sql
* @param params
* @return
*/
public Number getCount(String sql,Object[] params){
Number value =0;
Connection conn = null;
try {
conn = getConnection();
QueryRunner qRunner = new QueryRunner();
value = (Number) qRunner.query(conn, sql, new ScalarHandler(), params);
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
DbUtils.closeQuietly(conn);
}
return value;
}
/**
* 返回主键,通常是执行insert语句时返回当前的主键值
* 【注意,此方法没有关闭connection连接;需要在事务中关闭。 】
* @param sql
* @param params
* @return
* @throws Exception
*/
public Long getCurrentKey(String sql,Object[] params) throws Exception {
Connection conn = null;
Long key = 0l;
conn = getConnection();
QueryRunner qRunner = new QueryRunner();
key = (Long) qRunner.insert(conn,sql, new ScalarHandler(1), params);
return key;
}
/**
* 从线程池中:获取数据连接。
* @return
* @throws Exception
*/
public Connection getConnection(){
Connection conn = tl.get();
if(conn ==null){
conn = MyDataSource.getConnection();
}
return conn;
}
/***********事务处理方法************/
/**
* 开启事务
*/
public static void beginTranscation(){
Connection conn = tl.get();
try {
conn = MyDataSource.getConnection();
conn.setAutoCommit(false);
} catch (SQLException e) {
e.printStackTrace();
}
tl.set(conn);
}
/**
* 结束事务
* @throws SQLException
*/
public static void endTranscation(){
Connection conn = tl.get();
try {
conn.commit();
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 回滚
* @throws SQLException
*/
public static void rollback(){
Connection conn = tl.get();
try {
conn.rollback();
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 事务处理,关闭资源
* @throws SQLException
*/
public static void closeConn(){
Connection conn = tl.get();
try {
if(conn != null){
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
tl.remove();
}
}
10,实体类
package com.hpe.bean;
/**
* user对象实体类 t_user表对应的实体类。 面对对象的思想。
* 1、实现view层和控制层数据交互。
* 2、控制层和业务层之间的数据交互。
* 3、数据层和dao之间的数据对应。
*
* 使用的DBUtil ,数据库 表中的列 和实体类的属性,一一对应。
* @author Administrator
*
*/
public class User {
private int id; //主键
private String username;// 用户名
private String pwd;// 密码
private String sex;// 性别
private String love;// 爱好
private String birthday;// 生日
private String address;// 地址
private String email;// 邮箱
private String createDate;// 数据创建时间
private String updateDate;// 数据修改时间
public User() {
// TODO Auto-generated constructor stub
}
public User(String username, String pwd) {
super();
this.username = username;
this.pwd = pwd;
}
public User(String username, String pwd, String sex, String love, String birthday, String address, String email,
String updateDate) {
super();
this.username = username;
this.pwd = pwd;
this.sex = sex;
this.love = love;
this.birthday = birthday;
this.address = address;
this.email = email;
this.updateDate = updateDate;
}
public User(String username, String pwd, String sex, String love, String birthday, String address,
String email, String createDate, String updateDate) {
super();
this.username = username;
this.pwd = pwd;
this.sex = sex;
this.love = love;
this.birthday = birthday;
this.address = address;
this.email = email;
this.createDate = createDate;
this.updateDate = updateDate;
}
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 getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getLove() {
return love;
}
public void setLove(String love) {
this.love = love;
}
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getCreateDate() {
return createDate;
}
public void setCreateDate(String createDate) {
this.createDate = createDate;
}
public String getUpdateDate() {
return updateDate;
}
public void setUpdateDate(String updateDate) {
this.updateDate = updateDate;
}
}
11.工具类
package com.hpe.util;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
import com.mchange.v2.c3p0.ComboPooledDataSource;
/**
* 数据库连接池 c3p0数据源
*
* @author Administrator
*/
public class MyDataSource {
// 修改 数据库连接参
public static String DRIVER;
public static String URL;
public static String USER;
public static String PWD;
public static int maxPoolSize;
public static int minPoolSize;
public static int initialPoolSize;
public static int checkoutTimeout;
private static final String filePath = "db.properties";
private static ComboPooledDataSource cpDataSource = null;
// 加载驱动
static {
try {
// 读取配置文件,加载JDBC四大参数
Properties config = new Properties();
config.load(MyDataSource.class.getClassLoader().getResourceAsStream(filePath));
DRIVER = config.getProperty("drivername");
URL = config.getProperty("url");
USER = config.getProperty("username");
PWD = config.getProperty("password");
maxPoolSize = Integer.parseInt(config.getProperty("maxPoolSize"));
minPoolSize = Integer.parseInt(config.getProperty("minPoolSize"));
initialPoolSize = Integer.parseInt(config.getProperty("initialPoolSize"));
checkoutTimeout = Integer.parseInt(config.getProperty("checkoutTimeout"));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**************** c3p0 数据库连接池 启动方法 ******************/
private static void c3p0DataSource() throws Exception {
cpDataSource = new ComboPooledDataSource();
cpDataSource.setDriverClass(DRIVER);
cpDataSource.setJdbcUrl(URL);
cpDataSource.setUser(USER);
cpDataSource.setPassword(PWD);
cpDataSource.setMaxPoolSize(maxPoolSize);
cpDataSource.setMinPoolSize(minPoolSize);
cpDataSource.setInitialPoolSize(initialPoolSize);
cpDataSource.setCheckoutTimeout(checkoutTimeout);
}
/**
* c3p0数据库连接入
*
* @return
* @throws Exception
*/
public static Connection getConnection() {
Connection conn = null;
try {
if (cpDataSource == null) {
c3p0DataSource();
}
if(conn == null){
conn = cpDataSource.getConnection();
}
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}
}
12,配置文件db.properties
drivername=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/login_db?useUnicode=true&characterEncoding=utf-8
username=root
password=admin
maxPoolSize=20
minPoolSize=5
initialPoolSize=10
checkoutTimeout=10000
13,相应的js和css样式文件后续放上
包含:calendar.js
jquery-3.1.1.min.js
14,相应的jar文件
15,总结
此次登录小项目用到了很多以前没注意到的东西,思想还是MVC分层的思想,数据库连接部分使用的是C3P0,同时还用到了apache的duutils工具类,servlet部分主要用到了转发和重定向,此外还牵扯到数据的集中传递方式,在后续的博客中会详细来讲,list列表遍历显示部分舍弃了以往的java代码与html代码混合的模式,采用的主要是EL表达式和jstl标签,总的来说还是受益匪浅的。
16,项目下载链接
链接:https://pan.baidu.com/s/1YP9_E5QLGWsMZGv-1B0k7g 密码:rc9v