1、JdbcUtil
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
import org.apache.commons.dbcp.BasicDataSource;
/**
* 管理连接的工具类
*/
public class JdbcUtil {
// 定义数据库连接信息
private static String className;
private static String url;
private static String user;
private static String password;
private static BasicDataSource dataSource;
private static int initialSize;
private static int maxActive;
private static int minIdle;
private static int maxWait;
private JdbcUtil(){}
// 加载驱动程序
static{
try {
initParameter();
dataSource = new BasicDataSource();
dataSource.setDriverClassName(className);
dataSource.setUrl(url);
dataSource.setUsername(user);
dataSource.setPassword(password);
dataSource.setInitialSize(initialSize);
dataSource.setMaxActive(maxActive);
dataSource.setMinIdle(minIdle);
dataSource.setMaxWait(maxWait);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 解析属性文件
* @throws IOException
*/
public static void initParameter() throws IOException{
Properties prop = new Properties();
prop.load(JdbcUtil.class.getClassLoader()
.getResourceAsStream("db.properties"));//属性文件
className = prop.getProperty("jdbc.classname");
url = prop.getProperty("jdbc.url");
user = prop.getProperty("jdbc.user");
password = prop.getProperty("jdbc.password");
String strInitialSize = prop.getProperty("ds.initialSize");
initialSize = Integer.parseInt(strInitialSize);
maxActive = Integer.parseInt(prop.getProperty("ds.maxActive"));
minIdle = Integer.parseInt(prop.getProperty("ds.minIdle"));
maxWait = Integer.parseInt(prop.getProperty("ds.maxWait"));
}
/**
* 创建连接
*/
public static Connection getConn() throws SQLException{
Connection conn = dataSource.getConnection();
return conn;
}
/**
* 关闭连接
*/
public static void close(Connection conn){
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
/**
* 测试
* @throws SQLException
*/
public static void main(String[] args) throws SQLException {
Connection conn = getConn();
conn = getConn();
conn = getConn();
conn = getConn();
conn = getConn();
System.out.println(conn);
}
}
db.properties
jdbc.classname=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/数据库名?useUnicode=true&characterEncoding=UTF-8&useSSl=false&serverTimezone=Asia/Shanghai
jdbc.user=root
jdbc.password=数据库密码
ds.initialSize=30
ds.maxActive=100
ds.minIdle=5
ds.maxWait=500
2、 BaseDao
BaseDao
public class BaseDao {
public void updateData(String sql,Object...params) throws SQLException{
Connection conn = null;
try {
conn = JdbcUtil.getConn();
PreparedStatement pstmt = conn.prepareStatement(sql);
if(params!=null){
for(int i=0;i<params.length;i++){
pstmt.setObject(i+1, params[i]);
}
}
pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
throw e;
}finally{
JdbcUtil.close(conn);
}
}
public ResultSet findData(String sql,Object...params) throws SQLException{
ResultSet rs = null;
Connection conn = null;
CachedRowSet crs = null;
try {
conn = JdbcUtil.getConn();
ThreadLocal<Connection> local
= new ThreadLocal<Connection>();
local.set(conn);
PreparedStatement pstmt = conn.prepareStatement(sql);
if(params!=null){
for(int i=0;i<params.length;i++){
pstmt.setObject(i+1, params[i]);
}
}
rs = pstmt.executeQuery();
// 将基于连接的结果集数据转存到基于缓存的结果集
crs = new CachedRowSetImpl();
crs.populate(rs);
} catch (SQLException e) {
e.printStackTrace();
throw e;
}finally{
JdbcUtil.close(conn);
}
return crs;
}
}
3、登录注册Dao
此处UserDao并未继承BaseDao。
public class UserDao {
/**
* 登录方法
* @param userName
* @return
*/
public User findUserByName(String userName) {
User user = null;//创建对象,后续如果能查询到对应用户,则user就是这个用户信息的载体
//或者说它就是用户
try {
//从JDBC工具类获取连接
Connection connection = JdbcUtils.getConnection();
//定义sql查询语句
String sql = "select id,userName,password from user2 where userName=?";
//预处理,传入sql语句
PreparedStatement preparedStatement = connection.prepareStatement(sql);
//1即第一个?处的值为后续传入的userName参数
preparedStatement.setString(1, userName);
//执行查询操作得到结果集
ResultSet resultset = preparedStatement.executeQuery();
//对结果集中的数据进行遍历
while (resultset.next()) {
//如果可以从数据库中查到人名,将其其它信息赋值给user
user = new User();
user.setId(resultset.getInt(1));
user.setUserName(resultset.getString(2));
user.setPassword(resultset.getString(3));
}
return user;//findUserByName方法的返回值
} catch (SQLException e) {
e.printStackTrace();
}
return null;//查不到就返回null
}
/**
* 注册方法
* @param userName
* @param password
* @return
*/
public int addUser(String userName,String password) {
Connection connection = null;
try {
connection = JdbcUtils.getConnection();
String sql = "insert into user2(userName,password) values(?,?)";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, userName);
preparedStatement.setString(2, password);
int row = preparedStatement.executeUpdate();//row是数据库受此次executeUpdate操作影响的行数,即更新了几行
//输入了一个user信息,肯定只有1行
return row;
} catch (SQLException e) {
e.printStackTrace();
}
return 0;
}
}
登录、注册Servlet
LoginServlet :
@WebServlet("/login.do")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public LoginServlet() {
// TODO Auto-generated constructor stub
}
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
HttpSession session = request.getSession();
//这两者是从前端界面传过来的用户名和密码
String userName = request.getParameter("userName");
String password = request.getParameter("password");
//调用UserDao 中的方法findUserByName,传入userName进行验证
User user = new UserDao().findUserByName(userName);
//如果返回了一个user且其userName,password与前端输入的一致,则登录成功,跳转到主页面main.html
if(user != null && userName.equals(user.getUserName()) && password.equals(user.getPassword())) {
response.sendRedirect("main.jsp");
session.setAttribute("userName", userName);//向前端传送登录者的用户名
}else if (user == null) {
//否则就不动
response.sendRedirect("login.jsp");
System.out.println("该用户不存在");
}else {
//要不就是有一者输错了
response.sendRedirect("login.jsp");
System.out.println("用户名或密码错误");
}
}
}
RegisterServlet
@WebServlet("/register.do")
public class RegisterServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
String userName = request.getParameter("userName");
String password = request.getParameter("password");
int result = new UserDao().addUser(userName, password);
//如果返回的是 1 ,则说明注册成功
if (result == 1) {
response.sendRedirect("login.jsp");
System.out.println("注册成功!登录");
}else {
response.sendRedirect("register.jsp");
System.out.println("用户名或密码为空,请重新输入");
}
}
@Override
public void destroy() {
System.out.println("服务器销毁了!");
}
}
4、登录前端
login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>登录</title>
<script type="text/javascript" src="js/jquery-1.11.1.js"></script>
<link rel="stylesheet" type="text/css" href="css/login.css">
<style type="text/css">
body{
background-image:url("./img/round.jpg");
background-size: 100%;
background-size: cover;
}
</style>
</head>
<body>
<form id="loForm" action="login.do" method="post">
<div id="div1">
<h1>登录</h1><br>
<p>姓名 <input id="userName" type="text"
placeholder="username" name="userName" onblur="isNameNull();">
<span id="unSpanMsg"></span></p><br>
<p>密码 <input id="password" type="password"
placeholder="password" name="password" onblur="isPasswordNull()">
<span id="pwdSpanMsg"></span></p><br>
<p><button type="submit" id="btn1">登录</button>
<button type="reset" id="btn2" onclick="test()">重置</button></p>
<a href="register.jsp">去注册</a>
</div>
</form>
</body>
<script type="text/javascript">
function isNameNull(){
var uName = $("input[id='userName']").val();
if(uName==""){
$("span[id='unSpanMsg']").html("用户名不可为空!").css("color","red");
return false;
}else{
return true;
}
}
function isPasswordNull(){
var uPwd = $("input[id='password']").val();
if(uPwd==""){
$("span[id='pwdSpanMsg']").html("密码不可为空").css("color","red");
return false;
}else{
return true;
}
}
loForm.onsubmit = function(){
return isNameNull() && isPasswordNull();
};
function test(){
window.location.reload();
}
</script>
</html>