本文主要介紹了一種基于JSP和MySQL實現用戶登錄注冊功能的實驗報告。
實驗目的:
熟練掌握JSP和MySQL的基本概念和使用,學會使用JSP和MySQL實現用戶登錄和注冊功能。
實驗內容:
1. 創建MySQL數據庫和表,表字段包括用戶名、密碼和用戶ID。
CREATE DATABASE user_db; USE user_db; CREATE TABLE user_tbl ( id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY, name VARCHAR(20) NOT NULL, password VARCHAR(20) NOT NULL );
2. 編寫登錄和注冊JSP頁面,提交表單時通過Servlet調用MySQL數據庫實現功能。
//登錄Servlet import java.io.*; import java.sql.*; import javax.servlet.ServletException; import javax.servlet.http.*; public class LoginServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String name = request.getParameter("name"); String password = request.getParameter("password"); try { Class.forName("com.mysql.jdbc.Driver"); Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/user_db", "root", "123456"); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT id FROM user_tbl WHERE name='" + name + "' AND password='" + password + "'"); if (rs.next()) { HttpSession session = request.getSession(); session.setAttribute("id", rs.getInt("id")); response.sendRedirect("welcome.jsp"); } else { response.sendRedirect("login.jsp?error=1"); } rs.close(); stmt.close(); conn.close(); } catch (Exception e) { e.printStackTrace(); } } } //注冊Servlet import java.io.*; import java.sql.*; import javax.servlet.ServletException; import javax.servlet.http.*; public class RegisterServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String name = request.getParameter("name"); String password = request.getParameter("password"); try { Class.forName("com.mysql.jdbc.Driver"); Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/user_db", "root", "123456"); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT id FROM user_tbl WHERE name='" + name + "'"); if (rs.next()) { response.sendRedirect("register.jsp?error=1"); } else { stmt.executeUpdate("INSERT INTO user_tbl(name,password) VALUES('" + name + "','" + password + "')"); response.sendRedirect("login.jsp"); } rs.close(); stmt.close(); conn.close(); } catch (Exception e) { e.printStackTrace(); } } }
3. 編寫歡迎頁面,可以顯示登錄用戶的用戶名。
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><%@ page import="javax.servlet.http.HttpSession" %>歡迎頁面 歡迎,<%= ((HttpSession)request.getSession()).getAttribute("name") %>
實驗結果:
實驗結果如下圖所示:
結論:
通過本次實驗,我們成功地利用JSP和MySQL實現了用戶登錄和注冊功能。實驗中較為關鍵的部分是與MySQL數據庫的交互,可以通過JDBC連接MySQL數據庫并執行相應的SQL語句來實現。