jsp&servlet&jdbc&mysql實現簡單的增刪查改(二)

對數據庫進行查詢操作

1.查詢指定記錄

以設計一個簡單的登錄界面爲例
步驟:
(1)啓動數據庫,選擇相應的表(此項操作可詳見上篇博客,此處我選擇的仍然是test數據庫下的t_user表)
當前表中所有記錄:
在這裏插入圖片描述
(2)打開eclipse,在當前項目中的WebContent目錄下新建一個jsp文件(我這裏命名爲signin.jsp),在源文件目錄下選擇合適的包新建一個Servlet文件(我這裏命名爲SigninServlet.java),以用作連接數據庫,處理登錄界面發送的請求參數等。
(3)選擇用戶進行登錄需要驗證的字段,相應的在jsp文件中編輯源代碼(此處我選擇的是使用username登陸,並進行密碼驗證;爲提高查詢效率,可在該列添加索引)。
在這裏插入圖片描述

signin.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>用戶登陸</title>
</head>
<body>
	<form action="/blog/SigninServlet" method="post">
		登錄名稱:<input name="username" type="text" /><br /><p></p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;碼:<input name="password" type="password" /><br />
	   <p><input type="submit" /></p>
	</form>
</body>
</html>

顯示效果:
在這裏插入圖片描述
(4)編輯SigninServlet.java源代碼

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//定義變量接收參數
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		
		//爲登陸時參數的輸入設置條件
		boolean error = false;
		String errorMsg = " ";
		if (StringUtils.isEmpty(username)) {
			error = true;
			errorMsg = "用戶名不允許爲空";
		} else if (StringUtils.isEmpty(password)) {
			error = true;
			errorMsg = "密碼不允許爲空";
		}
		//如果上述條件不滿足,則跳轉到error.jsp(源代碼可見上篇博客),並給出相應提示
		if (error) {
			request.setAttribute("errorMsg", errorMsg);
			RequestDispatcher dispatcher = request.getRequestDispatcher("error.jsp");
			dispatcher.forward(request, response);
			return;
		}
		
		
		Connection connection = null;
		Statement statement = null;
		try {
			//連接數據庫,創建Statment接口
			connection = (Connection) DBUtil.getConnection();
			statement = (Statement) connection.createStatement();
			//準備sql語句
			String sql = "select * from t_user where username = '"+username+"' and password = '"+password+"'";
			System.out.println(sql);
			// 執行sql語句
			ResultSet resultSet =  statement.executeQuery(sql);
			resultSet.last();
			//判斷登陸是否成功,如果成功則轉到success.jsp頁面,如失敗則跳轉到error.jsp頁面,給出提示
			int rowCount = resultSet.getRow();
			if (rowCount <= 0) {
				request.setAttribute("errorMsg", "用戶名或密碼錯誤");
				RequestDispatcher dispatcher = request.getRequestDispatcher("error.jsp");
				dispatcher.forward(request, response);
				return;
			}
			request.setAttribute("msg", "登陸成功");
			RequestDispatcher dispatcher = request.getRequestDispatcher("success.jsp");
			dispatcher.forward(request, response);
			return;
			//捕獲執行try操作中的異常
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			
			//關閉數據庫連接和Statement接口
		} finally {
			if (connection != null) {
				try {
					connection.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if (statement != null) {
				try {
					statement.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}

		request.setAttribute("errorMsg", "系統異常");
		RequestDispatcher dispatcher = request.getRequestDispatcher("error.jsp");
		dispatcher.forward(request, response);
	}

}

success.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>status</title>
</head>
<body>

	<h1 style="color: red; text-align: center;">
	${msg}<!-- EL表達式 -->
	</h1>
	<a href="/blog/showUsers">查看所有註冊用戶</a><!-- 設置了一個鏈接,用於直接跳轉到查看所有用戶信息頁面 -->
</body>
</html>

如果登錄成功則頁面顯示:
在這裏插入圖片描述

2.查詢表中所有記錄

鑑於很多步驟都與前面的相同,所以這裏就不做詳細說明,只簡單補充

(1)定義usreList.jsp文件用於顯示所有用戶信息界面
需導入jstl-1.2.jar包和standard-1.1.2.jar包(網上下載後直接copy到lib目錄下)

usreList.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
     <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>所有用戶信息</title>
</head>
<body>
<table>
	<tr>
		<th>id</th>
		<th>郵箱</th>
		<th>電話號碼</th>
		<th>用戶名</th>
		<th>顯示暱稱</th>
		<th>密碼</th>
		<th>創建時間</th>
		<th>更新時間</th>
	</tr>
	<!-- -jstl表達式 -->
<c:forEach items="${userList}" var="u" varStatus="status">
  <tr >
    <td>${u.id}
    </td>
    <td>${u.email}
    </td>
    <td>${u.phoneNumber}
    </td>
    <td>${u.username}
    </td>
    <td>${u.nickname}
    </td>
    <td>${u.password}
    </td>
     
    <td> <fmt:formatDate value="${u.createTime}" pattern="yyyy-MM-dd HH:mm:ss" />
    </td>
    <td><fmt:formatDate value="${u.updateTime}" pattern="yyyy-MM-dd HH:mm:ss" />
    </td>
  </tr>
</c:forEach>
</table>
</body>
</html>

(2)定義ShowUsersServlet處理請求
ShowUsersServlet

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		Connection connection = null;
		Statement statement = null;
		try {
			connection = (Connection) DBUtil.getConnection();
			statement = (Statement) connection.createStatement();
			// 準備sql語句
			String sql = "SELECT * FROM t_user";//sql語句,不區分大小寫
			System.out.println(sql);
			
			ResultSet resultSet = statement.executeQuery(sql);
			List<User> userList = new ArrayList<User>();//封裝不限長度的數組
			//遍歷結果
			while (resultSet.next()) {
				User user = new User();
				user.setId(resultSet.getLong("id"));
				user.setEmail(resultSet.getString("email"));
				user.setPhoneNumber(resultSet.getString("phone_number"));
				user.setUsername(resultSet.getString("username"));
				user.setNickname(resultSet.getString("nickname"));
				user.setPassword(resultSet.getString("password"));
				user.setCreateTime(resultSet.getTimestamp("create_time"));
				user.setUpdateTime(resultSet.getTimestamp("update_time"));
				userList.add(user);
			}
			request.setAttribute("userList", userList);
			RequestDispatcher dispatcher = request.getRequestDispatcher("userList.jsp");
			dispatcher.forward(request, response);
			return;
		
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			//
		} finally {
			if (connection != null) {
				try {
					connection.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if (statement != null) {
				try {
					statement.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		request.setAttribute("errorMsg", "系統異常");
		RequestDispatcher dispatcher = request.getRequestDispatcher("error.jsp");
		dispatcher.forward(request, response);
	}

完成登錄後點擊鏈接顯示:
在這裏插入圖片描述

拓展
JDBC resultSet關於時間的顯示
(1)resultSet.getDate(); 顯示日期部分——> yyyy -mm-dd
(2)resultSet.getTime(); 顯示時間部分——> hh:mm:ss
(3)resultSet.getTime(); 顯示日期和時間——> yyyy -mm-dd hh:mm:ss

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章