==========網頁列表顯示界面stuList.jsp============== <%@ page import="java.util.List" %> <%@ page import="com.ibeifeng.student.Student" %> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>stuList</title> </head> <body> <% List<Student> list = (List<Student>)request.getAttribute("list"); //獲取從doList02傳遞過來的記錄總條數 String tdc = request.getAttribute("totalDataCount").toString(); //獲取從doList02傳遞過來的總頁面數 String tPage = request.getAttribute("totalPage").toString(); // String cPage = request.getAttribute("curPage").toString(); int totalDataCount = 0; int totalPage = 0; int cuPage = 0; int chooseSize = 5; if(tdc != null && !"".equals(tdc)){ totalDataCount = Integer.parseInt(tdc); } if(tPage != null && !"".equals(tPage)){ totalPage = Integer.parseInt(tPage); } if(cPage != null && !"".equals(cPage)){ cuPage = Integer.parseInt(cPage); } %> <a href="addStu.jsp">新增學員</a> <form method="post" action="doList02.jsp"> 姓名:<input type="text" name="name"> <input type="submit" value="查詢"> <table width="100%" border="1px solid black"> <tr> <td>學號</td> <td>姓名</td> <td>密碼</td> <td>性別</td> <td>郵箱</td> <td>操做</td> </tr> <% for(Student stu : list){ %> <tr> <td><%=stu.getStu_id()%></td> <td><%=stu.getStu_name()%></td> <td><%=stu.getPwd()%></td> <td><%=stu.getSex()%></td> <td><%=stu.getEmail()%></td> <td><a href="updateStu.jsp?sid=<%=stu.getStu_id()%>">修改</a> | <a href="doDel.jsp?sid=<%=stu.getStu_id()%>">刪除</a></td> </tr> <% }%> <tr> <td colspan="6" align="center"> <%if(cuPage > 1){%> <a href="doList02.jsp?curPage=<%=1%>">首頁</a> <a href="doList02.jsp?curPage=<%=cuPage-1%>">上一頁</a> <%}%> <%for(int i=0; i<totalPage; i++){%> <a href="doList02.jsp?curPage=<%=i+1%>"><%=i+1%></a> <%}%> <%if(cuPage < totalPage){%> <a href="doList02.jsp?curPage=<%=cuPage+1%>">下一頁</a> <a href="doList02.jsp?curPage=<%=totalPage%>">末頁</a> <%}%> <%=(cuPage + "/" + totalPage)%> <input type="text" name="chooseCurPage"> <select name="choosePageSize"> <option value="5" >5</option> <option value="10">10</option> <option value="20">20</option> </select> </td> </tr> </table> </form> </body> </html> ===========網頁列表顯示處理界面doList02.jsp========== <%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ page import="com.ibeifeng.student.Student" %> <%@ page import="java.util.ArrayList" %> <%@ page import="java.util.List" %> <%@ page import="com.ibeifeng.student.BaseDao2" %> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <% request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); List<Student> list = null; int pageSize = 5; //頁面顯示的記錄條數,初始值設爲5條 int curPage = 1; //當前頁面數,初始值設爲1 String cuPage = request.getParameter("curPage"); //獲取從顯示頁面傳遞過來的當前頁面值 String choosePageSize = request.getParameter("choosePageSize"); //獲取從頁面傳遞過來的頁面容量 String chooseCurPage = request.getParameter("chooseCurPage"); String name = request.getParameter("name"); if(name == null){ name = ""; } System.out.print("name"+name); if(choosePageSize != null && !"".equals(choosePageSize)){ pageSize = Integer.parseInt(choosePageSize); } if(cuPage != null && !"".equals(cuPage)){ curPage = Integer.parseInt(cuPage); } if(chooseCurPage != null && !"".equals(chooseCurPage)){ curPage = Integer.parseInt(chooseCurPage); } BaseDao2 bd = new BaseDao2(); System.out.print("name2:"+name+","+"curPage:"+curPage+","+"pageSize:"+pageSize); list = bd.page(name,curPage,pageSize); //調用分頁方法,獲得分頁查詢集合 int totalDataCount = bd.dataCount(); //查詢到的總記錄數 int totalPage = (totalDataCount % pageSize == 0)? (totalDataCount/pageSize):(totalDataCount/pageSize+1); request.setAttribute("chooseSize",pageSize); request.setAttribute("curPage",curPage); //將當前頁面編號傳遞到stuList頁面 request.setAttribute("totalPage",totalPage); //將總頁面數傳遞到stuList頁面 request.setAttribute("totalDataCount",totalDataCount); //將總記錄數傳遞到stuList頁面 request.setAttribute("list",list); System.out.print("list:"+list); request.getRequestDispatcher("stuList.jsp").forward(request,response); %> ==============修改頁面updateStu.jsp============= <%@ page import="com.ibeifeng.student.StudentDao" %> <%@ page import="com.ibeifeng.student.Student" %> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <% request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); //獲取前端頁面傳遞的參數 String sid = request.getParameter("sid"); //該參數由stuList頁面的<a href="updateStu.jsp?sid=stu.getStudentId()">傳遞過來 //建立StudentDao對象 StudentDao stuDao = new StudentDao(); Student stu = stuDao.getStuByStuId(sid); if(stu != null){ request.setAttribute("stu",stu); } %> <html> <head> <title>新增學員信息</title> </head> <body> <form action="doUpdate.jsp" method="post"> <table align="center" border="1px solid black"> <tr> <td>學號</td> <td><input type="text" name="stuId" readonly="readonly" value="<%=stu.getStu_id()%>"> </td> </tr> <tr> <td>姓名</td> <td><input type="text" name="stuName" value="<%=stu.getStu_name()%>"></td> </tr> <tr> <td>密碼</td> <td><input type="password" name="pwd" value="<%=stu.getPwd()%>"></td> </tr> <tr> <td>性別</td> <td> <input type="radio" name="gender" value="0" <%if(stu.getSex() == 0){%>checked="checked"<%}%>>女 <input type="radio" name="gender" value="1" <%if(stu.getSex() == 1){%>checked="checked"<%}%>>男 </td> </tr> <tr> <td>郵箱</td> <td><input type="text" name="email" value="<%=stu.getEmail()%>"></td> </tr> <tr> <td colspan="2"> <input type="submit" name="submit" value="保存"> <input type="button" name="return" value="取消"> </td> </tr> </table> </form> </body> </html> =============修改處理部分doUpdate.jsp============ <%@ page import="com.ibeifeng.student.Student" %> <%@ page import="com.ibeifeng.student.BaseDao2" %> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <% request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); BaseDao2 bd = new BaseDao2(); String sql = "update student set stu_name=?,pwd=?,sex=?,email=? where stu_id=?"; String stuid = request.getParameter("stuId"); int sid = Integer.parseInt(stuid); String name = request.getParameter("stuName"); String pwd = request.getParameter("pwd"); String gender = request.getParameter("gender"); int gen = Integer.parseInt(gender); String email = request.getParameter("email"); Object [] obj = {name, pwd, gender, email, sid}; int result = bd.update(sql,obj, Student.class); if(result > 0){ request.getRequestDispatcher("doList02.jsp").forward(request,response); }else{ request.getRequestDispatcher("updateStu.jsp?sno="+stuid).forward(request,response); } %> ===============刪除處理部分doDel.jsp============ <%@ page import="com.ibeifeng.student.BaseDao2" %> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <% request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); String sid = request.getParameter("sid"); BaseDao2 bd = new BaseDao2(); bd.del(sid); request.getRequestDispatcher("doList02.jsp").forward(request,response); %> ===============新增頁面addStu.jsp============== <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>新增學員信息</title> </head> <body> <form action="doSave.jsp" method="post"> <table align="center" border="1px solid black"> <tr> <td>學號</td> <td><input type="text" name="stuId" > </td> </tr> <tr> <td>姓名</td> <td><input type="text" name="stuName" ></td> </tr> <tr> <td>密碼</td> <td><input type="password" name="pwd" ></td> </tr> <tr> <td>性別</td> <td> <input type="radio" name="gender" value="0">女 <input type="radio" name="gender" value="1">男 </td> </tr> <tr> <td>郵箱</td> <td><input type="text" name="email" ></td> </tr> <tr> <td colspan="2"> <input type="submit" name="submit" value="保存"> <input type="button" name="return" value="取消"> </td> </tr> </table> </form> </body> </html> =============新增信息保存處理doSave.jsp=========== <%@ page import="com.ibeifeng.student.ConfigUtil" %> <%@ page import="java.sql.DriverManager" %> <%@ page import="java.sql.Connection" %> <%@ page import="java.sql.PreparedStatement" %> <%@ page import="java.sql.ResultSet" %> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <% request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); Class.forName(new ConfigUtil().getValue("driver")); Connection conn = DriverManager.getConnection( new ConfigUtil().getValue("url"),new ConfigUtil().getValue("username"),new ConfigUtil().getValue("password")); String sql = "insert into student(stu_id,stu_name,pwd,sex,email) values(?,?,?,?,?)"; PreparedStatement ps = conn.prepareStatement(sql); String rid = request.getParameter("stuId"); int id = Integer.parseInt(rid); ps.setInt(1,id); ps.setString(2,request.getParameter("stuName")); ps.setString(3,request.getParameter("pwd")); ps.setInt(4,1); ps.setString(5,request.getParameter("email")); int isSuccess = ps.executeUpdate(); System.out.print(isSuccess); if(isSuccess <= 0){ System.out.print("新增有誤,請重試"); request.getRequestDispatcher("/stuInfo/addStu.jsp").forward(request,response); }else{ request.getRequestDispatcher("/stuInfo/doList02.jsp").forward(request,response); } if(ps != null){ ps.close(); } if(conn != null){ conn.close(); } %> =============通用方法類BaseDao2============== package com.ibeifeng.student; import java.lang.reflect.Field; import java.sql.*; import java.util.ArrayList; import java.util.List; /* * 通用查詢、更新升級版 * */ public class BaseDao2 { static { try { Class.forName(ConfigUtil.getValue("driver")); } catch (ClassNotFoundException e) { e.printStackTrace(); } } public Connection getConn(){ try { return DriverManager.getConnection(ConfigUtil.getValue("url"), ConfigUtil.getValue("username"), ConfigUtil.getValue("password")); } catch (SQLException e) { e.printStackTrace(); return null; } } public void close(ResultSet rs, PreparedStatement ps, Connection conn){ try { if(rs != null) { rs.close(); } if(ps != null){ ps.close(); } if(conn != null){ conn.close(); } } catch (SQLException e) { e.printStackTrace(); } } /* * 返回一條查詢記錄 * 輸入參數Object[] obj中存放sql語句中變量的值 * */ public Object search(String sql, Object[] obj, Class<?> clz){ Connection conn = getConn(); PreparedStatement ps = null; ResultSet rs = null; try { ps = conn.prepareStatement(sql); if(obj != null && obj.length>0){ for(int i=0; i<obj.length; i++) { ps.setObject(i + 1, obj[i]); } } rs = ps.executeQuery(); if(!rs.next()){ return null; } /* * 在此處應該要給對象賦值,但遇到了如下問題 * 如何肯定列數? * 如何肯定列名? * 如何肯定查詢的是哪一個對象? * */ return doResultSet(rs,clz); } catch (SQLException e) { throw new RuntimeException(); }finally { close(null, ps, conn); } } /* * 運用java反射機制,編寫通用類,Class<?>表示不知道傳入的會是什麼類型的數據,所以用?代替 * */ public Object doResultSet(ResultSet rs, Class<?> clz){ Object bean = null; try { bean = clz.newInstance(); //對象實例化 ResultSetMetaData metaData = rs.getMetaData(); //獲取元數據 int colCount = metaData.getColumnCount(); //獲取列數 for(int i=0; i<colCount; i++){ Object colValue = rs.getObject(i+1); //獲取列的值 String colName = metaData.getColumnName(i+1); Field f = clz.getDeclaredField(colName); f.setAccessible(true); //取消某些檢測 f.set(bean,colValue); //將從數據庫獲取的值傳遞給bean對象 } } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } catch (NoSuchFieldException e) { e.printStackTrace(); } return bean; } /* * 查詢對象爲List,即有多條查詢記錄 * */ public Object searchList(String sql,Object[] obj,Class<?> clz){ PreparedStatement ps = null; ResultSet rs = null; Connection conn = getConn(); try { ps = conn.prepareStatement(sql); if(obj != null && obj.length>0) { for (int i = 0; i < obj.length; i++) { ps.setObject(i + 1, obj[i]); } } rs = ps.executeQuery(); if(!rs.next()){ return null; } return doResultSetList(rs, clz); } catch (SQLException e) { e.printStackTrace(); return null; }finally { close(rs,ps,conn); } } public List<Object> doResultSetList(ResultSet rs,Class<?> clz){ List<Object> list = new ArrayList<Object>(); try { while(rs.next()) { Object bean = clz.newInstance(); ResultSetMetaData metaData = rs.getMetaData(); int colCount = metaData.getColumnCount(); for (int i = 0; i < colCount; i++) { String colName = metaData.getColumnName(i + 1); Object colValue = rs.getObject(i + 1); Field f = clz.getDeclaredField(colName); f.setAccessible(true); f.set(bean, colValue); } list.add(bean); } } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } catch (NoSuchFieldException e) { e.printStackTrace(); } return list; } public int update(String sql, Object[] obj, Class<Student> studentClass){ Connection conn = getConn(); PreparedStatement ps = null; try { ps = conn.prepareStatement(sql); if(obj != null && obj.length>0) { for (int i = 0; i < obj.length; i++) { ps.setObject(i+1,obj[i]); } } return ps.executeUpdate(); } catch (SQLException e) { throw new RuntimeException(); }finally { close(null,ps,conn); } } //刪除功能 public int del(String stu_id){ String sql = "delete from student where stu_id = ?"; Connection conn = getConn(); PreparedStatement ps = null; try { ps = conn.prepareStatement(sql); ps.setString(1,stu_id); return ps.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException(); }finally { close(null,ps,conn); } } //分頁查詢 public List<Student> page(int pageIndex, int pageSize){ List<Student> list = null; String sql = "select * from student where stu_name like ? limit ?,?"; int index = (pageIndex-1)*pageSize; Object[] obj = {index, pageSize}; list = (List<Student>)searchList(sql,obj,Student.class); return list; } //重寫分頁查詢方法 public List<Student> page(String name, int pageIndex, int pageSize){ List<Student> list = null; String sql = "select * from student where stu_name like ? limit ?,?"; int index = (pageIndex-1)*pageSize; Object[] obj = {"%"+name+"%", index, pageSize}; list = (List<Student>)searchList(sql,obj,Student.class); return list; } //查詢數據的總條數 public int dataCount(){ String sql = "select count(*) from student"; int count=0; Connection conn = getConn(); PreparedStatement ps = null; ResultSet rs = null; try { ps = conn.prepareStatement(sql); rs = ps.executeQuery(); if(rs.next()){ count = rs.getInt(1); } } catch (SQLException e) { e.printStackTrace(); } return count; } } ==============數據對象類Student=============== package com.ibeifeng.student; public class Student { private int stu_id; private String stu_name; private String pwd; private int sex; private String email; public Student(){} public int getStu_id() { return stu_id; } public void setStu_id(int stu_id) { this.stu_id = stu_id; } public String getStu_name() { return stu_name; } public void setStu_name(String stu_name) { this.stu_name = stu_name; } public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd; } public int getSex() { return sex; } public void setSex(int sex) { this.sex = sex; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } @Override public String toString() { return "Student{" + "stu_id=" + stu_id + ", stu_name='" + stu_name + '\'' + ", pwd='" + pwd + '\'' + ", sex=" + sex + ", email='" + email + '\'' + '}'; } } ============獲取配置信息類================= package com.ibeifeng.student; import java.io.IOException; import java.io.InputStream; import java.util.Properties; public class ConfigUtil { //經過key獲取jdbc配置的value public static String getValue(String key){ Properties pro = new Properties(); //獲取流信息 InputStream is = ConfigUtil.class.getResourceAsStream("/jdbc.properties"); try { //加載流文件 pro.load(is); //獲取屬性值 return pro.getProperty(key); } catch (IOException e) { throw new RuntimeException(); } } } ==============此處只要關心經過id獲取類信息的方法getStuByStuId====== package com.ibeifeng.student; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class StudentDao { /* * Student Dao用於處理Student類 * */ Connection conn = null; PreparedStatement ps = null; public int updateStu(Student stu){ /* * 更新學員信息 * */ String sql = "update student set stu_name=?,pwd=?,sex=?,email=? where stu_id=?"; try { ps = BaseDao.getConn().prepareStatement(sql); ps.setString(1,stu.getStu_name()); ps.setString(2,stu.getPwd()); ps.setInt(3,stu.getSex()); ps.setString(4,stu.getEmail()); ps.setInt(5,stu.getStu_id()); return ps.executeUpdate(); } catch (SQLException e) { throw new RuntimeException(); }finally { BaseDao.close(null,ps,conn); } } public Student getStuByStuId(String stu_id){ String sql = "select * from student where stu_id=?"; Student stu = null; try { conn = BaseDao.getConn(); ps = conn.prepareStatement(sql); int sid = Integer.parseInt(stu_id); ps.setInt(1,sid); ResultSet rs = ps.executeQuery(); if(rs.next()){ stu = new Student(); stu.setStu_id(rs.getInt("stu_id")); stu.setStu_name(rs.getString("stu_name")); stu.setPwd(rs.getString("pwd")); stu.setSex(rs.getInt("sex")); stu.setEmail(rs.getString("email")); } } catch (SQLException e) { e.printStackTrace(); }finally { BaseDao.close(null,ps,conn); } return stu; } /* * 根據學號刪除學生信息 * */ public int delStu(String sid){ String sql = "delete from student where stu_id = ?"; conn = BaseDao.getConn(); try { ps = conn.prepareStatement(sql); int id = Integer.parseInt(sid); ps.setInt(1,id); return ps.executeUpdate(); } catch (SQLException e) { throw new RuntimeException(); } } }
==========網頁列表顯示界面stuList.jsp============== <%@ page import="java.util.List" %> <%@ page import="com.ibeifeng.student.Student" %> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>stuList</title> </head> <body> <% List<Student> list = (List<Student>)request.getAttribute("list"); //獲取從doList02傳遞過來的記錄總條數 String tdc = request.getAttribute("totalDataCount").toString(); //獲取從doList02傳遞過來的總頁面數 String tPage = request.getAttribute("totalPage").toString(); // String cPage = request.getAttribute("curPage").toString(); int totalDataCount = 0; int totalPage = 0; int cuPage = 0; int chooseSize = 5; if(tdc != null && !"".equals(tdc)){ totalDataCount = Integer.parseInt(tdc); } if(tPage != null && !"".equals(tPage)){ totalPage = Integer.parseInt(tPage); } if(cPage != null && !"".equals(cPage)){ cuPage = Integer.parseInt(cPage); } %> <a href="addStu.jsp">新增學員</a> <form method="post" action="doList02.jsp"> 姓名:<input type="text" name="name"> <input type="submit" value="查詢"> <table width="100%" border="1px solid black"> <tr> <td>學號</td> <td>姓名</td> <td>密碼</td> <td>性別</td> <td>郵箱</td> <td>操做</td> </tr> <% for(Student stu : list){ %> <tr> <td><%=stu.getStu_id()%></td> <td><%=stu.getStu_name()%></td> <td><%=stu.getPwd()%></td> <td><%=stu.getSex()%></td> <td><%=stu.getEmail()%></td> <td><a href="updateStu.jsp?sid=<%=stu.getStu_id()%>">修改</a> | <a href="doDel.jsp?sid=<%=stu.getStu_id()%>">刪除</a></td> </tr> <% }%> <tr> <td colspan="6" align="center"> <%if(cuPage > 1){%> <a href="doList02.jsp?curPage=<%=1%>">首頁</a> <a href="doList02.jsp?curPage=<%=cuPage-1%>">上一頁</a> <%}%> <%for(int i=0; i<totalPage; i++){%> <a href="doList02.jsp?curPage=<%=i+1%>"><%=i+1%></a> <%}%> <%if(cuPage < totalPage){%> <a href="doList02.jsp?curPage=<%=cuPage+1%>">下一頁</a> <a href="doList02.jsp?curPage=<%=totalPage%>">末頁</a> <%}%> <%=(cuPage + "/" + totalPage)%> <input type="text" name="chooseCurPage"> <select name="choosePageSize"> <option value="5" >5</option> <option value="10">10</option> <option value="20">20</option> </select> </td> </tr> </table> </form> </body> </html> ===========網頁列表顯示處理界面doList02.jsp========== <%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ page import="com.ibeifeng.student.Student" %> <%@ page import="java.util.ArrayList" %> <%@ page import="java.util.List" %> <%@ page import="com.ibeifeng.student.BaseDao2" %> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <% request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); List<Student> list = null; int pageSize = 5; //頁面顯示的記錄條數,初始值設爲5條 int curPage = 1; //當前頁面數,初始值設爲1 String cuPage = request.getParameter("curPage"); //獲取從顯示頁面傳遞過來的當前頁面值 String choosePageSize = request.getParameter("choosePageSize"); //獲取從頁面傳遞過來的頁面容量 String chooseCurPage = request.getParameter("chooseCurPage"); String name = request.getParameter("name"); if(name == null){ name = ""; } System.out.print("name"+name); if(choosePageSize != null && !"".equals(choosePageSize)){ pageSize = Integer.parseInt(choosePageSize); } if(cuPage != null && !"".equals(cuPage)){ curPage = Integer.parseInt(cuPage); } if(chooseCurPage != null && !"".equals(chooseCurPage)){ curPage = Integer.parseInt(chooseCurPage); } BaseDao2 bd = new BaseDao2(); System.out.print("name2:"+name+","+"curPage:"+curPage+","+"pageSize:"+pageSize); list = bd.page(name,curPage,pageSize); //調用分頁方法,獲得分頁查詢集合 int totalDataCount = bd.dataCount(); //查詢到的總記錄數 int totalPage = (totalDataCount % pageSize == 0)? (totalDataCount/pageSize):(totalDataCount/pageSize+1); request.setAttribute("chooseSize",pageSize); request.setAttribute("curPage",curPage); //將當前頁面編號傳遞到stuList頁面 request.setAttribute("totalPage",totalPage); //將總頁面數傳遞到stuList頁面 request.setAttribute("totalDataCount",totalDataCount); //將總記錄數傳遞到stuList頁面 request.setAttribute("list",list); System.out.print("list:"+list); request.getRequestDispatcher("stuList.jsp").forward(request,response); %> ==============修改頁面updateStu.jsp============= <%@ page import="com.ibeifeng.student.StudentDao" %> <%@ page import="com.ibeifeng.student.Student" %> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <% request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); //獲取前端頁面傳遞的參數 String sid = request.getParameter("sid"); //該參數由stuList頁面的<a href="updateStu.jsp?sid=stu.getStudentId()">傳遞過來 //建立StudentDao對象 StudentDao stuDao = new StudentDao(); Student stu = stuDao.getStuByStuId(sid); if(stu != null){ request.setAttribute("stu",stu); } %> <html> <head> <title>新增學員信息</title> </head> <body> <form action="doUpdate.jsp" method="post"> <table align="center" border="1px solid black"> <tr> <td>學號</td> <td><input type="text" name="stuId" readonly="readonly" value="<%=stu.getStu_id()%>"> </td> </tr> <tr> <td>姓名</td> <td><input type="text" name="stuName" value="<%=stu.getStu_name()%>"></td> </tr> <tr> <td>密碼</td> <td><input type="password" name="pwd" value="<%=stu.getPwd()%>"></td> </tr> <tr> <td>性別</td> <td> <input type="radio" name="gender" value="0" <%if(stu.getSex() == 0){%>checked="checked"<%}%>>女 <input type="radio" name="gender" value="1" <%if(stu.getSex() == 1){%>checked="checked"<%}%>>男 </td> </tr> <tr> <td>郵箱</td> <td><input type="text" name="email" value="<%=stu.getEmail()%>"></td> </tr> <tr> <td colspan="2"> <input type="submit" name="submit" value="保存"> <input type="button" name="return" value="取消"> </td> </tr> </table> </form> </body> </html> =============修改處理部分doUpdate.jsp============ <%@ page import="com.ibeifeng.student.Student" %> <%@ page import="com.ibeifeng.student.BaseDao2" %> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <% request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); BaseDao2 bd = new BaseDao2(); String sql = "update student set stu_name=?,pwd=?,sex=?,email=? where stu_id=?"; String stuid = request.getParameter("stuId"); int sid = Integer.parseInt(stuid); String name = request.getParameter("stuName"); String pwd = request.getParameter("pwd"); String gender = request.getParameter("gender"); int gen = Integer.parseInt(gender); String email = request.getParameter("email"); Object [] obj = {name, pwd, gender, email, sid}; int result = bd.update(sql,obj, Student.class); if(result > 0){ request.getRequestDispatcher("doList02.jsp").forward(request,response); }else{ request.getRequestDispatcher("updateStu.jsp?sno="+stuid).forward(request,response); } %> ===============刪除處理部分doDel.jsp============ <%@ page import="com.ibeifeng.student.BaseDao2" %> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <% request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); String sid = request.getParameter("sid"); BaseDao2 bd = new BaseDao2(); bd.del(sid); request.getRequestDispatcher("doList02.jsp").forward(request,response); %> ===============新增頁面addStu.jsp============== <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>新增學員信息</title> </head> <body> <form action="doSave.jsp" method="post"> <table align="center" border="1px solid black"> <tr> <td>學號</td> <td><input type="text" name="stuId" > </td> </tr> <tr> <td>姓名</td> <td><input type="text" name="stuName" ></td> </tr> <tr> <td>密碼</td> <td><input type="password" name="pwd" ></td> </tr> <tr> <td>性別</td> <td> <input type="radio" name="gender" value="0">女 <input type="radio" name="gender" value="1">男 </td> </tr> <tr> <td>郵箱</td> <td><input type="text" name="email" ></td> </tr> <tr> <td colspan="2"> <input type="submit" name="submit" value="保存"> <input type="button" name="return" value="取消"> </td> </tr> </table> </form> </body> </html> =============新增信息保存處理doSave.jsp=========== <%@ page import="com.ibeifeng.student.ConfigUtil" %> <%@ page import="java.sql.DriverManager" %> <%@ page import="java.sql.Connection" %> <%@ page import="java.sql.PreparedStatement" %> <%@ page import="java.sql.ResultSet" %> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <% request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); Class.forName(new ConfigUtil().getValue("driver")); Connection conn = DriverManager.getConnection( new ConfigUtil().getValue("url"),new ConfigUtil().getValue("username"),new ConfigUtil().getValue("password")); String sql = "insert into student(stu_id,stu_name,pwd,sex,email) values(?,?,?,?,?)"; PreparedStatement ps = conn.prepareStatement(sql); String rid = request.getParameter("stuId"); int id = Integer.parseInt(rid); ps.setInt(1,id); ps.setString(2,request.getParameter("stuName")); ps.setString(3,request.getParameter("pwd")); ps.setInt(4,1); ps.setString(5,request.getParameter("email")); int isSuccess = ps.executeUpdate(); System.out.print(isSuccess); if(isSuccess <= 0){ System.out.print("新增有誤,請重試"); request.getRequestDispatcher("/stuInfo/addStu.jsp").forward(request,response); }else{ request.getRequestDispatcher("/stuInfo/doList02.jsp").forward(request,response); } if(ps != null){ ps.close(); } if(conn != null){ conn.close(); } %> =============通用方法類BaseDao2============== package com.ibeifeng.student; import java.lang.reflect.Field; import java.sql.*; import java.util.ArrayList; import java.util.List; /* * 通用查詢、更新升級版 * */ public class BaseDao2 { static { try { Class.forName(ConfigUtil.getValue("driver")); } catch (ClassNotFoundException e) { e.printStackTrace(); } } public Connection getConn(){ try { return DriverManager.getConnection(ConfigUtil.getValue("url"), ConfigUtil.getValue("username"), ConfigUtil.getValue("password")); } catch (SQLException e) { e.printStackTrace(); return null; } } public void close(ResultSet rs, PreparedStatement ps, Connection conn){ try { if(rs != null) { rs.close(); } if(ps != null){ ps.close(); } if(conn != null){ conn.close(); } } catch (SQLException e) { e.printStackTrace(); } } /* * 返回一條查詢記錄 * 輸入參數Object[] obj中存放sql語句中變量的值 * */ public Object search(String sql, Object[] obj, Class<?> clz){ Connection conn = getConn(); PreparedStatement ps = null; ResultSet rs = null; try { ps = conn.prepareStatement(sql); if(obj != null && obj.length>0){ for(int i=0; i<obj.length; i++) { ps.setObject(i + 1, obj[i]); } } rs = ps.executeQuery(); if(!rs.next()){ return null; } /* * 在此處應該要給對象賦值,但遇到了如下問題 * 如何肯定列數? * 如何肯定列名? * 如何肯定查詢的是哪一個對象? * */ return doResultSet(rs,clz); } catch (SQLException e) { throw new RuntimeException(); }finally { close(null, ps, conn); } } /* * 運用java反射機制,編寫通用類,Class<?>表示不知道傳入的會是什麼類型的數據,所以用?代替 * */ public Object doResultSet(ResultSet rs, Class<?> clz){ Object bean = null; try { bean = clz.newInstance(); //對象實例化 ResultSetMetaData metaData = rs.getMetaData(); //獲取元數據 int colCount = metaData.getColumnCount(); //獲取列數 for(int i=0; i<colCount; i++){ Object colValue = rs.getObject(i+1); //獲取列的值 String colName = metaData.getColumnName(i+1); Field f = clz.getDeclaredField(colName); f.setAccessible(true); //取消某些檢測 f.set(bean,colValue); //將從數據庫獲取的值傳遞給bean對象 } } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } catch (NoSuchFieldException e) { e.printStackTrace(); } return bean; } /* * 查詢對象爲List,即有多條查詢記錄 * */ public Object searchList(String sql,Object[] obj,Class<?> clz){ PreparedStatement ps = null; ResultSet rs = null; Connection conn = getConn(); try { ps = conn.prepareStatement(sql); if(obj != null && obj.length>0) { for (int i = 0; i < obj.length; i++) { ps.setObject(i + 1, obj[i]); } } rs = ps.executeQuery(); if(!rs.next()){ return null; } return doResultSetList(rs, clz); } catch (SQLException e) { e.printStackTrace(); return null; }finally { close(rs,ps,conn); } } public List<Object> doResultSetList(ResultSet rs,Class<?> clz){ List<Object> list = new ArrayList<Object>(); try { while(rs.next()) { Object bean = clz.newInstance(); ResultSetMetaData metaData = rs.getMetaData(); int colCount = metaData.getColumnCount(); for (int i = 0; i < colCount; i++) { String colName = metaData.getColumnName(i + 1); Object colValue = rs.getObject(i + 1); Field f = clz.getDeclaredField(colName); f.setAccessible(true); f.set(bean, colValue); } list.add(bean); } } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } catch (NoSuchFieldException e) { e.printStackTrace(); } return list; } public int update(String sql, Object[] obj, Class<Student> studentClass){ Connection conn = getConn(); PreparedStatement ps = null; try { ps = conn.prepareStatement(sql); if(obj != null && obj.length>0) { for (int i = 0; i < obj.length; i++) { ps.setObject(i+1,obj[i]); } } return ps.executeUpdate(); } catch (SQLException e) { throw new RuntimeException(); }finally { close(null,ps,conn); } } //刪除功能 public int del(String stu_id){ String sql = "delete from student where stu_id = ?"; Connection conn = getConn(); PreparedStatement ps = null; try { ps = conn.prepareStatement(sql); ps.setString(1,stu_id); return ps.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException(); }finally { close(null,ps,conn); } } //分頁查詢 public List<Student> page(int pageIndex, int pageSize){ List<Student> list = null; String sql = "select * from student where stu_name like ? limit ?,?"; int index = (pageIndex-1)*pageSize; Object[] obj = {index, pageSize}; list = (List<Student>)searchList(sql,obj,Student.class); return list; } //重寫分頁查詢方法 public List<Student> page(String name, int pageIndex, int pageSize){ List<Student> list = null; String sql = "select * from student where stu_name like ? limit ?,?"; int index = (pageIndex-1)*pageSize; Object[] obj = {"%"+name+"%", index, pageSize}; list = (List<Student>)searchList(sql,obj,Student.class); return list; } //查詢數據的總條數 public int dataCount(){ String sql = "select count(*) from student"; int count=0; Connection conn = getConn(); PreparedStatement ps = null; ResultSet rs = null; try { ps = conn.prepareStatement(sql); rs = ps.executeQuery(); if(rs.next()){ count = rs.getInt(1); } } catch (SQLException e) { e.printStackTrace(); } return count; } } ==============數據對象類Student=============== package com.ibeifeng.student; public class Student { private int stu_id; private String stu_name; private String pwd; private int sex; private String email; public Student(){} public int getStu_id() { return stu_id; } public void setStu_id(int stu_id) { this.stu_id = stu_id; } public String getStu_name() { return stu_name; } public void setStu_name(String stu_name) { this.stu_name = stu_name; } public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd; } public int getSex() { return sex; } public void setSex(int sex) { this.sex = sex; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } @Override public String toString() { return "Student{" + "stu_id=" + stu_id + ", stu_name='" + stu_name + '\'' + ", pwd='" + pwd + '\'' + ", sex=" + sex + ", email='" + email + '\'' + '}'; } } ============獲取配置信息類================= package com.ibeifeng.student; import java.io.IOException; import java.io.InputStream; import java.util.Properties; public class ConfigUtil { //經過key獲取jdbc配置的value public static String getValue(String key){ Properties pro = new Properties(); //獲取流信息 InputStream is = ConfigUtil.class.getResourceAsStream("/jdbc.properties"); try { //加載流文件 pro.load(is); //獲取屬性值 return pro.getProperty(key); } catch (IOException e) { throw new RuntimeException(); } } } ==============此處只要關心經過id獲取類信息的方法getStuByStuId====== package com.ibeifeng.student; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class StudentDao { /* * Student Dao用於處理Student類 * */ Connection conn = null; PreparedStatement ps = null; public int updateStu(Student stu){ /* * 更新學員信息 * */ String sql = "update student set stu_name=?,pwd=?,sex=?,email=? where stu_id=?"; try { ps = BaseDao.getConn().prepareStatement(sql); ps.setString(1,stu.getStu_name()); ps.setString(2,stu.getPwd()); ps.setInt(3,stu.getSex()); ps.setString(4,stu.getEmail()); ps.setInt(5,stu.getStu_id()); return ps.executeUpdate(); } catch (SQLException e) { throw new RuntimeException(); }finally { BaseDao.close(null,ps,conn); } } public Student getStuByStuId(String stu_id){ String sql = "select * from student where stu_id=?"; Student stu = null; try { conn = BaseDao.getConn(); ps = conn.prepareStatement(sql); int sid = Integer.parseInt(stu_id); ps.setInt(1,sid); ResultSet rs = ps.executeQuery(); if(rs.next()){ stu = new Student(); stu.setStu_id(rs.getInt("stu_id")); stu.setStu_name(rs.getString("stu_name")); stu.setPwd(rs.getString("pwd")); stu.setSex(rs.getInt("sex")); stu.setEmail(rs.getString("email")); } } catch (SQLException e) { e.printStackTrace(); }finally { BaseDao.close(null,ps,conn); } return stu; } /* * 根據學號刪除學生信息 * */ public int delStu(String sid){ String sql = "delete from student where stu_id = ?"; conn = BaseDao.getConn(); try { ps = conn.prepareStatement(sql); int id = Integer.parseInt(sid); ps.setInt(1,id); return ps.executeUpdate(); } catch (SQLException e) { throw new RuntimeException(); } } }