使用idea開發javaWeb應用程序的思路(實現用戶的增刪改查)
在2.7 節基礎上,這一節實現瞭用戶的增刪改查操作。
完整工程代碼:
鏈接: https://pan.baidu.com/s/1zSGMvSQa-ihwEN5pP4vW6w 提取碼: dpw8
工程目錄結構如下:
1、添加/修改用戶頁面
在webapp下新建目錄user,用於存放用戶相關的頁面。
添加和修改使用的是同一個頁面,通過url中的參數控制是否是修改操作。
後臺通過是否傳遞瞭id進行判斷新增還是修改。
新建:add.html,代碼如下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>登錄頁面</title> <link rel="stylesheet" type="text/css" href="../css/my.css" rel="external nofollow" rel="external nofollow" > <script type="text/javascript" src="../js/my.js"></script> </head> <body> <div id="main-container" > <div id="div-header" > <h3 style="margin-bottom:0;">歡迎進入我的網站</h3> </hr> <p> 天將降大任於斯人也,必先苦其心志,勞其筋骨,餓其體膚,空乏其身,行拂亂其所為,所以動心忍性,曾益其所不能。——孟子 </p> </div> <div id="div-content" > <h3 style="margin-bottom:0;">添加用戶</h3> <form id="userAddForm" class="userAddForm" action="addUser" method="post"> <input id="id" type="hidden" name="id" /> <p>登錄賬號: <input id="uname" type="text" name="uname" /></p> <p>真實姓名: <input id="realName" type="text" name="realName" /></p> <p>選擇性別: <select id="sex" name="sex" style="width:170px"> <option id="option_m" value ="男">男</option> <option id="option_w" value ="女">女</option> </select></p> <p>登錄密碼: <input id="pwd" type="password" name="pwd" /></p> <p>確認密碼: <input id="pwdRepeat" type="password" name="pwdRepeat" /></p> <input type="button" value="提交" onclick="submitAddUser()"/> </form> </div> </div> <script type="text/javascript"> //檢查輸入是否為非空 function submitAddUser() { var uname = document.getElementById("uname").value;//獲取輸入的用戶名的值 var pwd = document.getElementById("pwd").value;//獲取輸入的密碼值 var pwdRepeat = document.getElementById("pwdRepeat").value;//獲取輸入確認密碼值 var realName = document.getElementById("realName").value;//獲取輸入的姓名值 var sex = document.getElementById("sex").value;//獲取輸入的性別值 if(uname == "" || pwd == "" || pwdRepeat == "" || realName == "" || sex == "" ){ alert("請將信息填寫完整後再提交。"); return; } if( pwd != pwdRepeat){ alert("兩次密碼輸入不一致,請重新輸入。"); } document.getElementById("userAddForm").submit(); //輸入不為空則跳轉到主頁面 } //從url中獲取參數 function getQueryVariable(variable) { var query = window.location.search.substring(1); console.log(query); var vars = query.split("&"); for (var i=0;i<vars.length;i++) { var pair = vars[i].split("="); if(pair[0] == variable){return decodeURI(pair[1]);} } return(false); } //判斷參數是否為true,不為true則彈窗提示密碼錯誤。 var bool = getQueryVariable("success"); var operation = getQueryVariable("operation"); if(bool == "false" && operation=="addUser"){ alert("操作失敗。"); }else if(bool == "true" && operation=="addUser"){ alert("操作成功。"); } showOld(); //從url中獲取參數,回顯 function showOld() { var uname = getQueryVariable("uname"); var realName = getQueryVariable("realName"); var id = getQueryVariable("id"); var sex = getQueryVariable("sex"); var pwd = getQueryVariable("pwd"); if(id != "" && id != null){ document.getElementById("uname").value=uname; document.getElementById("pwd").value=pwd; document.getElementById("pwdRepeat").value = pwd; document.getElementById("realName").value = realName; document.getElementById("id").value = id; if(sex == "男"){ document.getElementById("option_m").selected = true; }else{ document.getElementById("option_w").selected = true; } } } </script> </body> </html>
2、查詢用戶頁面
在user目錄下新建list.jsp,代碼如下:
<%@page import="java.util.ArrayList"%> <%@page import="com.my.site.UserEntity"%> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <title>我的網站</title> <meta charset="utf-8"> <link rel="stylesheet" type="text/css" href="../css/my.css" rel="external nofollow" rel="external nofollow" > </head> <body> <!-- jsp 頁面可以內嵌 java代碼--> <% ArrayList<UserEntity> all = ( ArrayList<UserEntity>)session.getAttribute("all"); %> <div id="main-container" > <div id="div-header" > <h3 style="margin-bottom:0;">用戶查詢</h3> </hr> <p> 天將降大任於斯人也,必先苦其心志,勞其筋骨,餓其體膚,空乏其身,行拂亂其所為,所以動心忍性,曾益其所不能。——孟子 </p> </div> <div id="div-content" > <table border="1" class="table" > <tr> <td>編號</td> <td>用戶名</td> <td>密碼</td> <td>真實姓名</td> <td>性別</td> <td>註冊時間</td> <td>操作</td> </tr> <% for(UserEntity user:all) {%> <tr> <td ><%=user.getId() %></td> <td><%=user.getUname() %></td> <td><%=user.getPwd() %></td> <td><%= user.getRealName() %></td> <td><%= user.getSex() %></td> <td><%= user.getAdd_time() %></td> <td><a href="del?id=<%=user.getId()%>%20" rel="external nofollow" >刪除</a> <a href="add.html?id=<%=user.getId()%>&uname=<%=user.getUname()%>&pwd=<%=user.getPwd()%>&realName=<%=user.getRealName()%>&sex=<%=user.getSex()%>" rel="external nofollow" >修改</a> </td> </tr> <%} %> </table> <p> 當前時間: <%= (new java.util.Date()).toLocaleString()%> </p> </div> </div> <script type="text/javascript"> //點擊按鈕跳轉到登錄頁面 function toAddUser() { window.location.href="user/add.html" rel="external nofollow" ; } function toSearchUser() { window.location.href="user/list" rel="external nofollow" ; } </script> </body> </html>
3、編寫後臺邏輯-添加/修改
新建:UserAdd類
package com.my.site; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @WebServlet("/user/addUser") public class UserAdd extends HttpServlet { /** req 攜帶瞭請求相關信息,包括各種配置和請求參數; resp:攜帶返回相關信息 */ @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //從請求對象中獲取請求參數:是從前端 usr/add.html頁面的 userAddForm 表單提交過來的 String uname = new String(req.getParameter("uname").getBytes("ISO-8859-1"),"utf-8"); String pwd = new String(req.getParameter("pwd").getBytes("ISO-8859-1"),"utf-8"); String realName = new String(req.getParameter("realName").getBytes("ISO-8859-1"),"utf-8"); String sex = new String(req.getParameter("sex").getBytes("ISO-8859-1"),"utf-8"); String pwdRepeat = new String(req.getParameter("pwdRepeat").getBytes("ISO-8859-1"),"utf-8"); String id_str = req.getParameter("id"); boolean bool = false; //如果有id,就執行更新操作,沒有id則執行新增操作 if(null != id_str && !"".equals(id_str)){ int id = Integer.parseInt(req.getParameter("id")); bool = MySqlOperator.updateUser(id,uname, pwd, realName, sex); }else { bool = MySqlOperator.addUser(uname, pwd, realName, sex); } resp.setContentType("text/html;charset=UTF-8"); if(bool){ //跳轉到主頁面,並攜帶請求體,返回體對象。 resp.sendRedirect("add.html?operation=addUser&success=true"); }else{ //校驗失敗則跳轉到登錄頁面 resp.sendRedirect("add.html?operation=addUser&success=false"); } } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req, resp); } }
4、編寫後臺邏輯-查詢
新建 UserList 類
package com.my.site; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; import java.util.List; @WebServlet("/user/list") public class UserList extends HttpServlet { /** req 攜帶瞭請求相關信息,包括各種配置和請求參數; resp:攜帶返回相關信息 */ @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { List<UserEntity> all = MySqlOperator.listAllUser(); HttpSession session = req.getSession(); session.setAttribute("all",all); resp.setContentType("text/html;charset=UTF-8"); resp.sendRedirect("list.jsp"); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req, resp); } }
5、編寫後臺邏輯-刪除
新建UserDel
package com.my.site; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @WebServlet("/user/del") public class UserDel extends HttpServlet { /** req 攜帶瞭請求相關信息,包括各種配置和請求參數; resp:攜帶返回相關信息 */ @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //從請求對象中獲取請求參數:是從前端 usr/add.html頁面的 userAddForm 表單提交過來的 int id = Integer.parseInt(req.getParameter("id").trim()); MySqlOperator.delUser(id); resp.setContentType("text/html;charset=UTF-8"); resp.sendRedirect("list"); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req, resp); } }
6、 編寫數據庫操作
package com.my.site; import java.sql.*; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; public class MySqlOperator { private static final String MYSQL_URL = "jdbc:mysql://localhost:3309/ztest?allowPublicKeyRetrieval=true&useSSL=false&serverTimezone=UTC"; private static final String MYSQL_NAME = "root"; private static final String MYSQL_PASSWORD = "MySql@8022"; private static Connection conn = null; private static Statement stt = null; static { try { Class.forName("com.mysql.cj.jdbc.Driver"); conn = DriverManager.getConnection(MYSQL_URL,MYSQL_NAME,MYSQL_PASSWORD); stt = conn.createStatement(); } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); } } /** * 根據用戶名和密碼檢查是否合法用戶, * @param uname * @param pwd * @return */ public static boolean loginChecked(String uname,String pwd){ try { Statement stt = conn.createStatement(); String sql = "select * from user where account='"+uname+"' and password = '"+pwd+"'";//這樣寫是有sql註入漏洞的,後面會用到 System.out.println(sql); ResultSet rs = stt.executeQuery(sql); while (rs.next()){ return true; } } catch ( SQLException e) { e.printStackTrace(); } return false; } /** * 添加用戶 */ public static boolean addUser(String uname,String pwd,String realName,String sex){ Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:sss"); String data_str = sdf.format(date); String sql = "insert into user(account,name,password,sex,add_time) values" + " ('"+uname+"','"+realName+"','"+pwd+"','"+sex+"','"+data_str+"')"; System.out.println(sql); try { if(conn.isValid(2)){ initConn(); } stt.execute(sql); return true; } catch (SQLException throwable) { throwable.printStackTrace(); return false; } } /**查詢所有用戶*/ public static List<UserEntity> listAllUser(){ String sql = "select * from user"; ResultSet rs = null; ArrayList<UserEntity> all = new ArrayList<>(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:sss"); try { rs = stt.executeQuery(sql); while (rs.next()){ UserEntity user = new UserEntity(); user.setUname(rs.getString("account")); user.setPwd(rs.getString("password")); user.setRealName(rs.getString("name")); user.setSex(rs.getString("sex")); user.setAdd_time(sdf.format(rs.getDate("add_time"))); user.setId(rs.getInt("id")); all.add(user); } System.out.println(sql); System.out.println("查詢條數:"+all.size()); return all; } catch (SQLException throwable) { throwable.printStackTrace(); } return all; } /**刪除用戶*/ public static boolean delUser(int id) { String sql = "delete from user where id="+id; try { stt.execute(sql); return true; } catch (SQLException throwable) { throwable.printStackTrace(); return false; } } /**用於 mysql 連接斷開後重連*/ public static void initConn(){ try { Class.forName("com.mysql.cj.jdbc.Driver"); conn = DriverManager.getConnection(MYSQL_URL,MYSQL_NAME,MYSQL_PASSWORD); stt = conn.createStatement(); } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); } } /**更新用戶信息*/ public static boolean updateUser(int id, String uname, String pwd, String realName, String sex) { Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:sss"); String data_str = sdf.format(date); String sql = "update user set account='"+uname+"',password='"+pwd+"',name='"+realName+"',sex='"+sex+"',add_time='"+data_str+"' where id="+id; System.out.println(sql); try { if(conn.isValid(2)){ initConn(); } stt.execute(sql); return true; } catch (SQLException throwable) { throwable.printStackTrace(); return false; } } }
7、 運行效果
到此這篇關於使用idea開發javaWeb應用程序的思路(實現用戶的增刪改查)的文章就介紹到這瞭,更多相關idea 開發javaweb應用程序內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!