1. 程式人生 > >Eclipse使用(七)—— 使用Eclipse建立JavaWeb專案並使用JDBC連線資料庫實現簡單的登陸註冊功能

Eclipse使用(七)—— 使用Eclipse建立JavaWeb專案並使用JDBC連線資料庫實現簡單的登陸註冊功能

一、建立資料庫表(這裡使用的是Mysql5.7)

DDL語句如下:
  1. CREATETABLE `tb_user` (  
  2.   `u_id` int(11) NOTNULL AUTO_INCREMENT COMMENT '使用者編號',  
  3.   `u_username` varchar(30) NOTNULL COMMENT '使用者名稱',  
  4.   `u_password` varchar(30) NOTNULL COMMENT '密碼',  
  5.   PRIMARYKEY (`u_id`)  
  6. ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;  

二、專案需要使用的jar示例


三、編寫持久層和業務層程式碼

專案src目錄結構預覽:


1、在src目錄下建立com.mengfei.entity包,並在包中建立實體類User

package com.mengfei.entity;

import java.io.Serializable;

public class User implements Serializable{
	private static final long serialVersionUID = 1L;
	
	private Integer uid;
	private String username;
	private String password;
	public Integer getUid() {
		return uid;
	}
	public void setUid(Integer uid) {
		this.uid = uid;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	@Override
	public String toString() {
		return "User{" +
				"uid=" + uid +
				", username='" + username + '\'' +
				", password='" + password + '\'' +
				'}';
	}
}

2、在com.mengfei包中建立dao包,並在包中建立類BaseDao

package com.mengfei.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class BaseDao {
	protected Connection conn;
	protected PreparedStatement ps;
	protected ResultSet rs;

	public Connection getConnection() {
		try {
			Class.forName("com.mysql.jdbc.Driver");
			conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/demo?useSSL=false", "alex", "123");
			//Class.forName("oracle.jdbc.driver.OracleDriver");
			//conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl", "alex", "123");
			/**
			 * com.mysql.jdbc.Driver是建立連線的驅動類,Oracle使用的是oracle.jdbc.driver.OracleDriver
			 * jdbc:mysql://localhost:3306/demo?useSSL=false是要連線的url地址,Oracle使用的是jdbc:oracle:thin:@localhost:1521:orcl
			 * localhost代表本地連線,如果使用遠端連線則要改成IP地址
			 * demo是要連線的mysql中資料庫的名字,Oracle中用的是例項orcl
			 * ?useSSL=false是引數,不寫也能連線,Oracle中不需要
			 * alex是要連線的使用者名稱
			 * 123是使用者的密碼
			 */
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return conn;
	}

	public void closeDB(ResultSet rs, PreparedStatement ps, Connection conn) {

		try {
			if (rs != null) {
				rs.close();
			}
			if (ps != null) {
				ps.close();
			}
			if (conn != null) {
				conn.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}

	}

	// 測試是否連線上資料庫
	public static void main(String[] args) {
		BaseDao dao = new BaseDao();
		System.out.println(dao.getConnection());
	}

}

3、在com.mengfei.dao包中建立介面UserDao

package com.mengfei.dao;

import com.mengfei.entity.User;

public interface UserDao {
	/**
	 * 使用者註冊
	 * @param user
	 * @return
	 */
	Integer register(User user);
	
	/**
	 * 使用者登陸
	 * @param user
	 * @return
	 */
	User login(User user);
}

4、在com.mengfei.dao包中建立impl包,並在包中建立類UserDaoImpl,該類繼承BaseDao,實現UserDao

package com.mengfei.dao.impl;

import java.sql.SQLException;

import com.mengfei.dao.BaseDao;
import com.mengfei.dao.UserDao;
import com.mengfei.entity.User;

public class UserDaoImpl extends BaseDao implements UserDao {

	@Override
	public Integer register(User user) {
		int row = 0;
		conn = getConnection();
		String sql = "insert into tb_user(u_username,u_password) values(?,?)";
		try {
			ps = conn.prepareStatement(sql);
			ps.setString(1, user.getUsername());
			ps.setString(2, user.getPassword());
			row = ps.executeUpdate();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			closeDB(rs, ps, conn);
		}
		return row;
	}

	@Override
	public User login(User user) {
		User u=null;
		conn=getConnection();
		String sql="select * from tb_user where u_username=? and u_password=?";
		try {
			ps=conn.prepareStatement(sql);
			ps.setString(1, user.getUsername());
			ps.setString(2, user.getPassword());
			rs = ps.executeQuery();
			while(rs.next()){
				u=new User();
				u.setUid(rs.getInt(1));
				u.setUsername(rs.getString(2));
				u.setPassword(rs.getString(3));
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			closeDB(rs, ps, conn);
		}
		return u;
	}

}

5、在com.mengfei包中建立biz包,並在包中建立介面UserBiz

package com.mengfei.biz;

import com.mengfei.entity.User;

public interface UserBiz {
	/**
	 * 使用者註冊
	 * @param username
	 * @param password
	 * @return
	 */
	Boolean register(String username, String password);

	/**
	 * 使用者登陸
	 * @param username
	 * @param password
	 * @return
	 */
	User login(String username, String password);
}

6、在com.mengfei.biz包中建立impl包,並在包中建立類UserBizImpl實現UserBiz

package com.mengfei.biz.impl;

import com.mengfei.biz.UserBiz;
import com.mengfei.dao.UserDao;
import com.mengfei.dao.impl.UserDaoImpl;
import com.mengfei.entity.User;

public class UserBizImpl implements UserBiz {

	private UserDao userDao = new UserDaoImpl();

	@Override
	public Boolean register(String username, String password) {
		User user = new User();
		user.setUsername(username);
		user.setPassword(password);
		Integer result = userDao.register(user);
		if (result > 0) {
			return true;
		}
		return false;
	}

	@Override
	public User login(String username, String password) {
		User user = new User();
		user.setUsername(username);
		user.setPassword(password);
		User u = userDao.login(user);
		return u;
	}

}

7、在com.mengfei包中建立servlet包,並在包中建立UserServlet

package com.mengfei.servlet;

import java.io.IOException;

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.mengfei.biz.UserBiz;
import com.mengfei.biz.impl.UserBizImpl;
import com.mengfei.entity.User;

@WebServlet("/UserServlet")
public class UserServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		UserBiz userBiz=new UserBizImpl();
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		String operate = request.getParameter("operate");
		if(!"".equals(username)&&!"".equals(password)&&!"".equals(operate)) {
			if("register".equals(operate)) {
				Boolean b = userBiz.register(username, password);
				if(b) {
					request.getRequestDispatcher("success.jsp").forward(request, response);
				}else {
					response.sendRedirect("index.jsp");
				}
			}else if("login".equals(operate)) {
				User user = userBiz.login(username, password);
				if(null!=user) {
					request.setAttribute("username", user.getUsername());
					request.getRequestDispatcher("success.jsp").forward(request, response);
				}else {
					response.sendRedirect("index.jsp");
				}
			}else {
				response.sendRedirect("index.jsp");
			}
		}else {			
			response.sendRedirect("index.jsp");
		}
	}

}

四、編寫表現層程式碼(web.xml檔案暫時不用管它)

1、在WebContent目錄中建立js目錄,將jquery-3.2.1.js檔案放進去

2、編寫index.jsp(放在WebContext目錄下)

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="js/jquery-3.2.1.js"></script>
</head>
<body>
	<form id="form" action="UserServlet" method="post" onsubmit="return checkUser1()">
		<input type="hidden" name="operate" id="operate">
		帳號:<input type="text" name="username" id="username"><br>
		密碼:<input type="password" name="password" id="password"><br>
		<input type="submit" value="註冊">
		<input id="login" type="button" value="登陸" onclick="checkUser2()">
	</form>
</body>
</html>
<script>
	//註冊使用表單提交事件進行驗證提交
    function checkUser1() {
        var username=$('#username').val();
        var password=$('#password').val();
        if(''==username){
            alert('使用者名稱不能為空!');
            return false;
        }
        if(''==password){
            alert('密碼不能為空!');
            return false;
        }
        $('#operate').val('register');
        return true;
    }
    //登陸使用單擊事件進行驗證提交
    function checkUser2() {
        var username=$('#username').val();
        var password=$('#password').val();
        if(''==username){
            alert('使用者名稱不能為空!');
            return false;
		}
		if(''==password){
            alert('密碼不能為空!');
            return false;
		}
		$('#operate').val('login');
        $('#form').get(0).action='UserServlet';
        $('#form').get(0).submit();
    }
</script>

3、在WebContent目錄下建立success.jsp檔案

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
    <c:if test="${empty username}">
        註冊成功!
    </c:if>

    <c:if test="${!empty username}">
        登陸成功!歡迎 ${username} !
    </c:if>
</body>
</html>

五、部署測試

1、右鍵點選本地server將專案新增到Tomcat中


2、啟動Tomcat,在瀏覽器中輸入localhost:8080/JDBCJavaWebDemo/index.jsp,顯示如下圖:


OK,到這裡就可以自己進行註冊和登陸測試啦