1、創建數據庫、表:
2、項目結構:
3、數據庫連接工具類 DBUtil :
public class DBUtil {
// table,對應數據庫的表
public static final String TABLE_PASSWORD = "account";
public static final String TABLE_USERINFO = "userinfo";
// connect to MySql database
public static Connection getConnect() {
String url = "jdbc:mysql://localhost:3306/android"; // 數據庫的Url,android代表數據庫名
Connection connecter = null;
try {
Class.forName("com.mysql.jdbc.Driver"); // java反射,固定寫法
//root 是數據庫的賬戶名稱,123456是賬戶密碼,改爲自己的
connecter = (Connection) DriverManager.getConnection(url, "root", "123456");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
System.out.println("SQLException: " + e.getMessage());
System.out.println("SQLState: " + e.getSQLState());
System.out.println("VendorError: " + e.getErrorCode());
}
return connecter;
}
}
4、處理註冊的 Servlet :
@WebServlet("/RegisterServlet")
public class RegisterServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public RegisterServlet() {
super();
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
// response.getWriter().append("Served at: ").append(request.getContextPath());
String account = request.getParameter("account"); // 從 request 中獲取名爲 account 的參數的值
String password = request.getParameter("password"); // 從 request 中獲取名爲 password 的參數的值
System.out.println("account:" + account + "\npassword:" + password); // 打印出來看一看
String resCode = "";
String resMsg = "";
String userId = "";
/* 這裏我們做一個最簡單的註冊邏輯,當然,你的實際業務可以相當複雜 */
try {
Connection connect = DBUtil.getConnect();
Statement statement = (Statement) connect.createStatement(); // Statement可以理解爲數據庫操作實例,對數據庫的所有操作都通過它來實現
ResultSet result;
String sqlQuery = "select * from " + DBUtil.TABLE_PASSWORD + " where userAccount='" + account + "'";
// 查詢類操作返回一個ResultSet集合,沒有查到結果時ResultSet的長度爲0
result = statement.executeQuery(sqlQuery); // 先查詢同樣的賬號(比如手機號)是否存在
if(result.next()){ // 已存在
resCode = "201";
resMsg = "該賬號已註冊,請使用此賬號直接登錄或使用其他賬號註冊";
userId = "";
} else { // 不存在
String sqlInsertPass = "insert into " + DBUtil.TABLE_PASSWORD + "(userAccount,userPassword) values('"+account+"','"+password+"')";
// 更新類操作返回一個int類型的值,代表該操作影響到的行數
int row1 = statement.executeUpdate(sqlInsertPass); // 插入帳號密碼
if(row1 == 1){
String sqlQueryId = "select userId from " + DBUtil.TABLE_PASSWORD + " where userAccount='" + account + "'";
ResultSet result2 = statement.executeQuery(sqlQueryId); // 查詢新增記錄的userId
if(result2.next()){
userId = result2.getInt("userId") + "";
}
int new_userId=Integer.valueOf(userId);
String sqlInsertInfo = "insert into " + DBUtil.TABLE_USERINFO + "(userId) values('" + new_userId + "')";
int row2 = statement.executeUpdate(sqlInsertInfo); // 在用戶信息表中插入剛註冊的Id
if(row2 == 1){ // 兩個表中都插入成功,從業務角度認定爲註冊成功
resCode = "100";
resMsg = "註冊成功";
}
} else {
resCode = "202";
resMsg = "用戶信息表插入錯誤";
userId = "";
}
}
} catch (SQLException e) {
e.printStackTrace();
}
HashMap<String, String> map = new HashMap<>();
map.put("resCode", resCode);
map.put("resMsg", resMsg);
map.put("userId", userId);
response.setContentType("text/html;charset=utf-8"); // 設置響應報文的編碼格式
PrintWriter pw = response.getWriter(); // 獲取 response 的輸出流
pw.println(map.toString()); // 通過輸出流把業務邏輯的結果輸出
pw.flush();
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
5、處理登陸的 Servlet :
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public LoginServlet() {
super();
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String code = "";
String message = "";
String account = request.getParameter("account");
String password = request.getParameter("password");
log(account + ";" + password);
Connection connect = DBUtil.getConnect();
try {
Statement statement = (Statement) connect.createStatement();
String sql = "select userId from " + DBUtil.TABLE_PASSWORD + " where userAccount='" + account
+ "' and userPassword='" + password + "'";
log(sql);
ResultSet result = statement.executeQuery(sql);
if (result.next()) { // 能查到該賬號,說明已經註冊過了
code = "200";
message = "登陸成功";
} else {
code = "100";
message = "登錄失敗,密碼不匹配或賬號未註冊";
}
} catch (SQLException e) {
e.printStackTrace();
}
response.setContentType("text/html;charset=utf-8"); // 設置響應報文的編碼格式,避免瀏覽器中輸出亂碼問題
response.getWriter().append("code:").append(code).append(";message:").append(message);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
6、運行測試:
瀏覽器中輸入要註冊的賬號、密碼:
通過 Navicat 查看數據庫表內容:
瀏覽器中輸入要登錄的賬號、密碼:
服務端環境搭建、編程到此結束,下面是客戶端的編程,請看下篇文章~
♥ 喜 歡 請 點 贊 喲 ♥ |
(●ˇ∀ˇ●) |