【個人學習筆記】使用Servlet實作簡單的登陸注冊功能
開發環境:IDEA2019、Tomcat7.0、Mysql5.5.5、Wampserver64
-
建立檔案
打開IDEA建立一個Java Web Application項目,選擇tomcat,輸入一些必要資訊直到finish。
【學習日記】使用Servlet實作簡單的登陸注冊功能 此次開發需要用到兩個jar包
JSP标準标簽庫(JSTL)
mysql-connector-java
選擇自己适合的版本下載下傳好之後在IDEA中導入 File -> Project Structure -> Project Settings -> Module -> Dependencies 點選+号添加jar包
【學習日記】使用Servlet實作簡單的登陸注冊功能 -
檔案目錄介紹
初始目錄下隻有一個src檔案夾(空)和web目錄,在src檔案夾下建立檔案目錄如圖所示
【學習日記】使用Servlet實作簡單的登陸注冊功能 其中:
dao 檔案夾下類主要處理與資料庫的互動,登入和注冊主要用到查詢和插入資料庫功能;
model 檔案夾主要存放實體類資訊,我們隻需要用到user實體類;
service 檔案夾主要存放一些業務類,個人了解為在dao層對資料庫進行操作時對資料進行一個預處理;
servlet 檔案夾主要作為控制層來處理表單發送的資料,即處理使用者的請求資訊;
test 檔案夾主要用于開發過程中測試功能;
util 檔案夾主要存放一些工具類,例如資料庫連接配接、資料處理方法等。
Web 檔案下主要存放需要用到的jsp檔案以及一些網頁的靜态資源;
-
連接配接資料庫工具類
在Util 工具類中,本次僅需要用到連接配接資料庫的功能,當然也可以在該工具類中聲明一個用于判斷資料是否有效的判斷類,但時間關系沒有用到。
建立一個class類DBUtil,主要用于連接配接資料庫和關閉連接配接
import java.sql.*;
public class DBUtil {
//建立連接配接
public static Connection getConnection() throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.jdbc.Driver");
Connection connection = //此處的3306對應安裝的mysql的端口号、asd對應選擇的資料庫名、最後兩個參數分别表示mysql使用者名和密碼
DriverManager.getConnection("jdbc:mysql://localhost:3306/asd?useSSL=false","root","");
return connection;
}
//關閉連接配接
public static void closeAll(ResultSet rs, Statement stmt, Connection conn) throws SQLException {
if(rs!=null){
rs.close();
}
if(stmt!=null){
stmt.close();
}
if(conn!=null){
conn.close();
}
}
}
連接配接好資料庫之後,在Dao目錄下建立一個用于通路資料庫的UserDao類,實作對資料庫的查詢和插入操作
import com.shixi.model.User;
import com.shixi.util.DBUtil;
import java.sql.*;
public class UseDao {
//登陸查詢資料庫
public User selectByName(String name) throws SQLException {
ResultSet rs = null;
Connection conn = null;
PreparedStatement pstmt = null;
DBUtil util = new DBUtil();
User user = new User();
try{
conn = util.getConnection();
pstmt = conn.prepareStatement("select * from user where name = ?");
pstmt.setString(1,name);
rs = pstmt.executeQuery();
while(rs.next()){
user.setId(rs.getInt(1)); //第幾個字段
user.setName(rs.getString(2));
user.setPassword(rs.getString(3));
user.setAge(rs.getString(4));
}
}catch(Exception e){
e.printStackTrace();
}finally {
util.closeAll(rs,pstmt,conn);
}
return user;
}
//注冊插入資料庫
public boolean insertUserInfo(String name, String password) throws SQLException, ClassNotFoundException {
ResultSet rs = null;
Connection conn = null;
PreparedStatement pstmt = null;
DBUtil util = new DBUtil();
boolean flag = true;
try {
conn = util.getConnection();
pstmt = conn.prepareStatement("insert into user values(null,?,?,null)");
pstmt.setString(1, name);
pstmt.setString(2, password);
pstmt.execute();
}catch(Exception e){
e.printStackTrace();
}finally {
util.closeAll(rs,pstmt,conn);
}
return flag;
}
}
【踩坑心得】:插入資料庫時需要使用pstmt.execute()方法而非查詢的query方法,并且傳回一個布爾值,當提取到的首條資料是存在的即傳回true否則傳回false,此處我們隻需要執行了該語句,不需要用到傳回的值,是以隻要執行了該語句,就設定傳回true。
此外此處的insert語句隻需要賬号和密碼,是以我們需要将資料庫中的id字段設定為自增長,并且将age字段設定為預設為空。
-
實體類和業務類
在model目錄下建立一個實體類User,聲明User中的各個屬性
public class User {
private int id;
private String name;
private String password;
private String age;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", password='" + password + '\'' +
", age='" + age + '\'' +
'}';
}
}
在Service目錄下建立一個處理User的業務類UserService,聯合dao一同使用對資料處理。
import com.shixi.dao.UseDao;
import com.shixi.model.User;
import java.sql.SQLException;
public class UserService {
static UseDao useDao = new UseDao();
public static User selectByName(String name) throws SQLException {
return useDao.selectByName(name);
}
public static boolean insertUserInfo(String name, String password) throws SQLException, ClassNotFoundException {
return useDao.insertUserInfo(name,password);
}
}
-
Servlet類
Servlet在web.xml檔案中進行配置,作為控制層對從jsp發送的表單資料進行處理,包含了doPost方法和doGet方法,LoginServlet和RegisterServlet分别處理登陸和注冊
LoginServlet
import com.shixi.model.User;
import com.shixi.service.UserService;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
public class LoginServlet extends HttpServlet {
UserService userService = new UserService();
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String name = req.getParameter("name");
String password = req.getParameter("password");
User user = null;
try {
user = userService.selectByName(name);
} catch (SQLException e) {
e.printStackTrace();
}
if(password.equals(user.getPassword())){
resp.getWriter().write("success");
}else{
resp.getWriter().write("failed");
}
}
}
RegisterServlet:
import com.shixi.model.User;
import com.shixi.service.UserService;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.SQLException;
public class RegisterServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp){
String name = req.getParameter("name");
String password = req.getParameter("password");
System.out.println(name+" "+password);
boolean flag = false;
try {
flag = UserService.insertUserInfo(name,password);
System.out.println(flag);
if(flag){
req.setAttribute("success","注冊成功,請登入");
req.getRequestDispatcher("index.jsp").forward(req,resp);
}else{
req.setAttribute("error","注冊失敗,請重試");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
-
jsp和web.xml配置
一共用到兩個jsp頁面,分别是login.jsp和register.jsp(這裡當初直接使用了index.jsp作為登陸界面,沒有重寫一個login)裡面就一些基礎的html布局,做的很簡單。
login.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>登陸</title>
</head>
<body style="margin:0px auto; width:900px; text-align: center">
<div >
<h1>登陸界面</h1>
<form action="${pageContext.request.contextPath}/login" method="post">
<div>
<%--@declare id="user"--%><label for="user">帳号: <input name="name" type="text"></label>
</div>
<div>
<%--@declare id="password"--%><label for="password">密碼: <input name="password" type="password"></label>
</div>
<div>
<input type="submit" value="登陸">
<input type="button" value="注冊"onclick="javascript:window.location.href='register.jsp'">
</div>
</form>
</div>
</body>
</html>
register.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>注冊</title>
</head>
<body style="margin:0px auto; width:900px; text-align: center">
<div>
<h1>注冊界面</h1>
<form action="${pageContext.request.contextPath}/register" method="post">
<div>
<%--@declare id="user"--%><label for="user">賬号: <input name="name" type="text"></label>
</div>
<div>
<%--@declare id="password"--%><label for="password">密碼: <input name="password" type="password"></label>
</div>
<div>
<input type="button" value="傳回"onclick="javascript:window.location.href='index.jsp'">
<input type="submit" value="注冊">
</div>
</form>
</div>
</body>
</html>
-
注冊和登陸結果
注冊過程和用到的類主要有如下關系
【學習日記】使用Servlet實作簡單的登陸注冊功能 運作結果:
register.jsp頁面
輸入賬号和密碼進行注冊,在資料庫中即可添加,添加成功後會自動跳轉到登陸界面【學習日記】使用Servlet實作簡單的登陸注冊功能 login.jsp頁面:【學習日記】使用Servlet實作簡單的登陸注冊功能 輸入剛才注冊的賬号密碼,登陸成功【學習日記】使用Servlet實作簡單的登陸注冊功能 【學習日記】使用Servlet實作簡單的登陸注冊功能 -
遇到的問題
(1) execute()和executeQuery()問題
executeQuery()主要用于查詢資料而execute()主要用于更新和插入資料。
(2)sql語句的規範問題
進行注冊時,之前用的語句為
就會語句報錯,後改成現UseDao中的
即可。
(3)Servlet配置問題
我在配置tomcat啟動的時候将url配置為目前deployment下的路徑,是以在jsp中的action的路徑沒有加上該部分,這裡找到一個便捷的路由配置方法,可以自動比對tomcat中配置的url。