用户登录案例实现
文章目錄
- 案例需求
- 需求功能分析
- 代碼實現
案例需求
在網站的首頁上,點擊登錄的鏈接,可以跳轉到登錄的頁面。在登錄的頁面中輸入用戶名和密碼,點擊登錄的案例,完成登錄的功能。
需求功能分析
代碼實現
數據庫
CREATE TABLE `user`(username VARCHAR(50),`password` VARCHAR(50));INSERT INTO `user` VALUES('tom','123'),('jerry','456');# 通過?戶名,密碼查詢 user表SELECT * FROM `user` WHERE username='tom' AND `password`='123' /* dbutils 使?哪個結果集 BeanHandler 查詢結果?個JavaBean BeanListHandler 查詢結果集是多個JavaBean,存儲List集合 ScalarHandler 單項值查詢 ColumnListHandler 查詢?個列數據存儲集合List<Object> */html頁面
<form action="/web01/user" method="post"> 用戶名:<input type="text" name="username" /> <br/> 密 碼:<input type="text" name="password" /> <br/> <input type="submit" /> </form>Servlet
public class UserServlet extends HttpServlet {protected void doGet(HttpServletRequest request, HttpServletResponseresponse) throws ServletException, IOException { /* 1.獲取??的傳遞過來的數據, (?戶名, 密碼) 2.使? (?戶名, 密碼) , 操作數據庫, 查找匹配的User信息 3.判斷User信息 是否為空 User為null, 代表 沒查到匹配的?戶信息, 打印 "登錄失敗, ?戶名或密 碼錯誤" user為不為Null, 代表 查到匹配的?戶信息, 打印"登錄成功" */ // 1.獲取??的傳遞過來的數據, (?戶名, 密碼)String username = request.getParameter("username");String password = request.getParameter("password"); // 2.使? (?戶名, 密碼) , 操作數據庫, 查找匹配的User信息QueryRunner qr = new QueryRunner(DruidUtils.getDataSource());String sql = "select * from user where username=? and password=?";User user = null;try {user = qr.query(sql, new BeanHandler<User>(User.class),username, password);} catch (SQLException e) {e.printStackTrace();} // 3.判斷User信息 是否為空if (user == null) { // User為null, 代表 沒查到匹配的?戶信息, 打印 "登錄失敗, ?戶名或密碼錯誤 "System.out.println("登錄失敗, ?戶名或密碼錯誤");response.getWriter().print("return false");} else { // user為不為Null, 代表 查到匹配的?戶信息, 打印"登錄成功"System.out.println("登錄成功");response.getWriter().print("return true");}}protected void doPost(HttpServletRequest request, HttpServletResponseresponse) throws ServletException, IOException {doGet(request, response);} }總結
- 上一篇: 如何显示日期和时间(电脑右下角显示日期和
- 下一篇: ServletContext接口