MVC_CRUD:操做數據庫實現增刪改查√ import java.io.Serializable; public class Student implements Serializable { private static final long serialVersionUID = 5289634478724041840L; private Integer stuId; private String stuName; private Integer stuAge; private Integer stuXueli; private String stuGender; private Double stuScore; private String stuDate; private String stuHobby; private String stuDes; public static long getSerialVersionUID() { return serialVersionUID; } public Integer getStuId() { return stuId; } public void setStuId(Integer stuId) { this.stuId = stuId; } public String getStuName() { return stuName; } public void setStuName(String stuName) { this.stuName = stuName; } public Integer getStuAge() { return stuAge; } public void setStuAge(Integer stuAge) { this.stuAge = stuAge; } public Integer getStuXueli() { return stuXueli; } public void setStuXueli(Integer stuXueli) { this.stuXueli = stuXueli; } public String getStuGender() { return stuGender; } public void setStuGender(String stuGender) { this.stuGender = stuGender; } public Double getStuScore() { return stuScore; } public void setStuScore(Double stuScore) { this.stuScore = stuScore; } public String getStuDate() { return stuDate; } public void setStuDate(String stuDate) { this.stuDate = stuDate; } public String getStuHobby() { return stuHobby; } public void setStuHobby(String stuHobby) { this.stuHobby = stuHobby; } public String getStuDes() { return stuDes; } public void setStuDes(String stuDes) { this.stuDes = stuDes; } @Override public String toString() { return "Student{" + "stuId=" + stuId + ", stuName='" + stuName + '\'' + ", stuAge=" + stuAge + ", stuXueli=" + stuXueli + ", stuGender='" + stuGender + '\'' + ", stuScore=" + stuScore + ", stuDate='" + stuDate + '\'' + ", stuHobby='" + stuHobby + '\'' + ", stuDes='" + stuDes + '\'' + '}'; } } import com.Model.Student; import java.util.List; public interface IStudentDao { //添加的方法 public int insert(Student student); //刪除的方法 public int delete(int stuId); //修改的方法 public int update(Student student); //查詢的方法,根據id去修改 public Student findFindy(int stuId); //查詢的方法:查詢全部的信息 public List<Student> finaAll(); } import com.Dao.IStudentDao; import com.Model.Student; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.handlers.BeanHandler; import org.apache.commons.dbutils.handlers.BeanListHandler; import javax.sql.DataSource; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; //Dao接口的實現類 public class StudentDaoimp implements IStudentDao { //建立一個全局的QueryRunner 對象、 //方法一: private QueryRunner qr; //方法二: private DataSource ds; public StudentDaoimp(DataSource ds){ qr=new QueryRunner(ds); } @Override public int insert(Student student) { String sql="insert into student(stuName,stuAge,stuXueli,stuGender,stuScore,stuDate,stuHobby,stuDes)values(?,?,?,?,?,?,?,?)"; Object[]prams={student.getStuName(),student.getStuAge(),student.getStuXueli(),student.getStuGender(),student.getStuScore(),student.getStuDate(),student.getStuHobby(),student.getStuDes()}; int i=0; try{ i=qr.update(sql,prams); }catch (SQLException ce){ ce.printStackTrace(); } return i; } @Override public int delete(int stuId) { String sql="delete from student where stuId=?"; Object[]prams={stuId}; int i=0; try{ i=qr.update(sql,prams); }catch (SQLException ce){ ce.printStackTrace(); } return i; } @Override public int update(Student student) { String sql="update student set stuName=?,stuAge=?,stuXueli=?,stuGender=?,stuScore=?,stuDate=?,stuHobby=?,stuDes=? where stuId=?"; Object[]prams={student.getStuName(),student.getStuAge(),student.getStuXueli(),student.getStuGender(),student.getStuScore(),student.getStuDate(),student.getStuHobby(),student.getStuDes(),student.getStuId()}; int i=0; try{ i=qr.update(sql,prams); }catch (SQLException ce){ ce.printStackTrace(); } return i; } @Override public Student findFindy(int stuId) { String sql="select * from student where stuId=?"; Object[]prams={stuId}; Student student=null; try{ student=qr.query(sql,new BeanHandler<Student>(Student.class),prams); }catch (SQLException ce){ ce.printStackTrace(); } return student; } @Override public List<Student> finaAll(){ String sql="select * from student"; List<Student>list=new ArrayList<>(); try{ list=qr.query(sql,new BeanListHandler<Student>(Student.class)); }catch (SQLException ce){ ce.printStackTrace(); } return list; } } 代理類 import com.Dao.IStudentDao; import com.Dao.imp.StudentDaoimp; import com.Model.Student; import com.Utils.DatabaseConnection; import javax.sql.DataSource; import java.util.List; public class StudentDaoProxy implements IStudentDao { private IStudentDao studentDao; private DataSource ds; public StudentDaoProxy(){ ds=DatabaseConnection.getDateSource(); studentDao=new StudentDaoimp(ds); } @Override public int insert(Student student) { int i=studentDao.insert(student); return i; } @Override public int delete(int stuId){ int i=studentDao.delete(stuId); return i; } @Override public int update(Student student) { int i=studentDao.update(student); return i; } @Override public Student findFindy(int stuId) { Student student=studentDao.findFindy(stuId); return student; } @Override public List<Student> finaAll() { List<Student>list=studentDao.finaAll(); return list; } }
import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Map; import java.util.Properties; /** * @PACKAGE_NAME: com.Model.utils * @ClASS_NAME: DaoFactory * @Description DAO工廠類 * @Author: Model * @DATE: 2019/8/23 15:34 * @Version : 1.0 **/ public class Daofactory { private static Properties p; //map集合用來充當緩存,key要和dao.properties中的key一致 //值,DAO接口的實例對象 private static Map<String,Object> cache; //初始化 static{ p=new Properties(); cache=new HashMap<>(); //加載dao.properties屬性文件 InputStream is=Thread.currentThread().getContextClassLoader().getResourceAsStream("dao.properties"); try { p.load(is); }catch (IOException ce){ ce.printStackTrace(); } } /** * 線程安全的泛型方法 * @param daoName 就是dao.properties屬性文件中key的名字 * @param daoClass 就是key所對應值得父接口或者接口的實現類 * @param <T> * @return */ public synchronized static<T> T getInstance(String daoName,Class daoClass){ //先從map集合中,根據KEY去查找,有沒有對應的值 T t=(T)cache.get(daoName); if(t==null){//說明map集合中不存在當前daoName鎖對應的鍵值對 //去屬性文件中查找指定KEY是否存在,若是存在,則獲取key所對應的值 //值就是某個DAO接口的實現類的全限定名 String className=p.getProperty(daoName); if(null!=className&&!"".equals(className)){//說明key-value存在 try { //把指定類的字節碼文件加載JVM虛擬機中 Class clazz = Class.forName(className); //經過反射機制調用類中無參數的構造方法建立clazz的對象 t=(T)daoClass.cast(clazz.getDeclaredConstructor().newInstance()); //把對象添加到map集合中 cache.put(daoName,t); }catch (Exception ce){ ce.printStackTrace(); } } } return t; } } import com.alibaba.druid.pool.DruidDataSource; import javax.sql.DataSource; import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Properties; //專門負責數據庫打開與關閉操做的類 public class DatabaseConnection { //建立阿里巴巴鏈接池對象 private static DruidDataSource ds; private static Properties P; static { ds=new DruidDataSource(); P=new Properties(); //讀取屬性文件 InputStream input=Thread.currentThread().getContextClassLoader().getResourceAsStream("druid.properties"); //加載P對象 try{ P.load(input); }catch(IOException ce){ ce.printStackTrace(); } //根據鍵獲取值 ds.setDriverClassName(P.getProperty("driverClass")); ds.setUrl(P.getProperty("url")); ds.setUsername(P.getProperty("user")); ds.setPassword(P.getProperty("password")); //配鏈接池的參數 ds.setInitialSize(Integer.parseInt(P.getProperty("initialSize"))); ds.setMinIdle(Integer.parseInt(P.getProperty("minIdle"))); ds.setMaxActive(Integer.parseInt(P.getProperty("maxActive"))); ds.setMaxWait(Integer.parseInt(P.getProperty("maxWait"))); ds.setTimeBetweenEvictionRunsMillis(Integer.parseInt(P.getProperty("timeBetweenEvictionRunsMillis"))); } public static DataSource getDateSource(){ return ds; } //獲取數據庫鏈接對象 public static Connection getConnection()throws SQLException { return ds.getConnection(); } //關閉數據庫鏈接對象之insert delete update的操做 public static void close(Connection con, Statement state)throws SQLException{ con.close();; state.close(); } //關閉數據庫鏈接的對象之 select 查找查詢的操做 public static void close(Connection con, Statement state, ResultSet set)throws SQLException{ set.close(); state.close(); con.close(); } //關閉獲取數據庫鏈接對象 public static void close(Connection con)throws SQLException{ con.close(); } // 關閉執行Statement執行SQL 語句的對象 public static void close(Statement state)throws SQLException{ state.close(); } //關閉結果集對象ResultSet對象 public static void close(ResultSet set)throws SQLException{ set.close(); } } import com.Dao.IStudentDao; import com.Factory.Daofactory; import com.Model.Student; import java.util.List; //業務層 //Daofactory:的做用是專門用來建立dao接口的實現類對象的。 public class StudentService { private IStudentDao studentDao= Daofactory.getInstance("UserDao",IStudentDao.class); //添加的方法: public int insert(Student student){ return studentDao.insert(student); } //刪除的方法; public int delete(int stuId){ return studentDao.delete(stuId); } //修改的方法: public int update(Student student){ return studentDao.update(student); } //查詢的方法: public Student findFindy(int stuId){ return studentDao.findFindy(stuId); } //查詢全部的方法: public List<Student> findAll(){ return studentDao.finaAll(); } } 服務器端:: import com.Model.Student; import com.Service.StudentService; 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; import java.io.PrintWriter; import java.util.List; @WebServlet("/mvc") public class MVC_Servlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //設置請求的編碼 req.setCharacterEncoding("UTF-8"); String method=req.getParameter("method"); if(null!=method&&!"".equals(method)){ if("stuAdd".equals(method)){ //調用添加的方法 addStu(req, resp); }else if("list".equals(method)){//查詢的方法 addList(req, resp); }else if("update".equals(method)){//修改的方法 stuaUpdate(req, resp); }else if("delete".equals(method)){//刪除的方法 studelete(req, resp); }else if("edit".equals(method)){//編輯的方法 stuedit(req,resp); } } } //學員信息添加的方法 protected void addStu(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //獲取請求的參數 String stuName=req.getParameter("stuName"); String stuAge=req.getParameter("stuAge"); String stuXueli=req.getParameter("stuXueli"); String stuGender=req.getParameter("stuGender"); String stuScore=req.getParameter("stuScore"); String stuDate=req.getParameter("stuDate"); String[]stuHobby=req.getParameterValues("stuHobby"); String stuDes=req.getParameter("stuDes"); //準備一個Student對象。獲得屬性的值 Student student=new Student(); student.setStuName(stuName); student.setStuAge(Integer.parseInt(stuAge)); student.setStuXueli(Integer.parseInt(stuXueli)); student.setStuGender(stuGender); student.setStuScore(Double.parseDouble(stuScore)); student.setStuDate(stuDate); StringBuilder stringBuilder=new StringBuilder(); for(String ss:stuHobby){ stringBuilder.append(ss); stringBuilder.append("-"); } student.setStuHobby(stringBuilder.toString()); student.setStuDes(stuDes); //建立業務層的對象 StudentService services=new StudentService(); //添加業務層的對象 int i=services.insert(student); //設置響應的內容的類型 resp.setContentType("text/html;charset=UTF-8"); //獲取字符輸出流 PrintWriter out=resp.getWriter(); if(i>0){ req.setAttribute("MSG","學員的信息添加成功"); }else{ req.setAttribute("MSG","學員的信息添加失敗"); } //請求分派到成功的頁面 req.getRequestDispatcher("success.jsp").forward(req,resp); } //學員信息的查詢頁面 protected void addList(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //建立業務層的對象 StudentService studentService=new StudentService(); //建立業務層對象添加到list集合中 List<Student>list=studentService.findAll(); //把list集合添加到請求域中 req.setAttribute("List",list); //把List集合請求分派到查詢成功的頁面 req.getRequestDispatcher("list.jsp").forward(req,resp); } //學員信息編輯的方法 protected void stuedit(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //或取請求的參數,根據id去編輯 String stuId=req.getParameter("stuId"); //建立業務層的對象 StudentService studentService=new StudentService(); Student student=studentService.findFindy(Integer.parseInt(stuId)); //把Student對象添加到請求域中 req.setAttribute("student",student); //請求分派到成功的頁面 req.getRequestDispatcher("edit.jsp").forward(req,resp); } //學員信息修改的方法 protected void stuaUpdate(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //設置請求中的編碼 req.setCharacterEncoding("UTF-8"); //根據id去修改,獲取請求中的參數 String stuId=req.getParameter("stuId"); String stuName=req.getParameter("stuName"); String stuAge=req.getParameter("stuAge"); String stuXueli=req.getParameter("stuXueli"); String stuGender=req.getParameter("stuGender"); String stuScore=req.getParameter("stuScore"); String stuDate=req.getParameter("stuDate"); String[]hobbys=req.getParameterValues("stuHobby"); String stuDes=req.getParameter("stuDes"); //建立業務層的對象。根據id去修改,返回的是一個Student對象 StudentService studentService=new StudentService(); Student student=studentService.findFindy(Integer.parseInt(stuId)); student.setStuName(stuName); student.setStuAge(Integer.parseInt(stuAge)); student.setStuXueli(Integer.parseInt(stuXueli)); student.setStuGender(stuGender); student.setStuScore(Double.parseDouble(stuScore)); student.setStuDate(stuDate); //愛好爲數組,必須用字符輸出流來輸出 StringBuilder builder=new StringBuilder(); for(String ss:hobbys){ builder.append(ss); builder.append("-"); } student.setStuHobby(builder.toString()); student.setStuDes(stuDes); int i=studentService.update(student); if(i>0){ req.setAttribute("MSG","學員的信息修改爲功"); }else{ req.setAttribute("MSG","學員的信息修改失敗"); } //請求分派到成功的頁面 req.getRequestDispatcher("success.jsp").forward(req,resp); } //學員信息刪除的方法 protected void studelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //獲取請求中的參數 String stuId=req.getParameter("stuId"); //建立業務層的對象 StudentService studentService=new StudentService(); int i=studentService.delete(Integer.parseInt(stuId)); if(i>0){ req.setAttribute("MSG","學員的信息刪除成功"); }else{ req.setAttribute("MSG","學員的信息刪除失敗"); } req.getRequestDispatcher("success.jsp").forward(req,resp); } } JSP前端的頁面:添加的頁面 <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>學員信息的添加頁面</title> </head> <body> <h2 style="color: red" align="center">學員信息的添加頁面</h2> <form action="mvc?method=stuAdd" method="post" class="form" onsubmit=" return lwj();"> <table> <tr> <td>用戶名:</td> <td> <input type="text" name="stuName" id="stuName" style="background: aqua" placeholder="請輸入用戶名"></br> </td> </tr> <tr> <td>年齡:</td> <td> <input type="text" name="stuAge" id="stuAge" style="background: aqua" placeholder="請輸入年齡"></br> </td> </tr> <tr> <td>學@歷:</td> <td> <select name="stuXueli" id="stuXueli"> <option value="0">小學</option> <option value="1">初中</option> <option value="2">高中</option> <option value="3">大學</option> </select> </td> </tr><br> <tr> <td>性 別:</td> <td> <input type="radio" name="stuGender" value="女">女 <input type="radio" name="stuGender" value="男">男</br> </td> <tr> <td>成@績:</td> <td> <input type="text" name="stuScore" id="stuScore" style="background: aqua" placeholder="請輸入成績"><br> </td> </tr> <tr> <td>生 日:</td> <td> <input type="date" name="stuDate" id="stuDate"></br> </td> </tr> <tr> <td>愛@好:</td> <td> <input type="checkbox" name="stuHobby" value="play">籃球 <input type="checkbox" name="stuHobby" value="sing">唱歌 <input type="checkbox" name="stuHobby" value="sleep">睡覺 </td><br> </tr> <tr> <td>文本框:</td> <td> <textarea cols="30" rows="20" name="stuDes" style="background: salmon"></textarea> </td> </tr> <tr> <td colspan="2" align="center"> <input type="submit" value="提交"> <input type="reset" value="重置"> </td> </tr> </table> </form> </body> </html> <script src="js/from.js"></script> JSP前端的頁面:查詢的頁面 <%@ page import="java.util.List" %> <%@ page import="com.Model.Student" %><%-- Created by IntelliJ IDEA. User: Lenovo-T410 Date: 2019/12/12 Time: 11:41 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>列表的顯示頁面</title> </head> <body> <h2 style="color: red">學員信息的查詢頁面</h2> <table width="100%" border="100%" style="background: blanchedalmond"> <tr> <th>ID</th> <th>姓名</th> <th>年齡</th> <th>學歷</th> <th>性別</th> <th>成績</th> <th>生日</th> <th>愛好</th> <th>簡介</th> <th>操做</th> </tr> <%--獲取Servlet請求域中的數據--%> <% List<Student>list=(List<Student>)request.getAttribute("List"); //作個驗證,爲了防止list集合報空指針異常,若是==0就等於0,不然返回他自己 int size=list.size()==0?0:list.size(); for(int i=0;i<size;i++){ Student student=list.get(i);%> <tr align="center"> <td> <%=student.getStuId()%> </td> <td> <%=student.getStuName()%> </td> <td> <%=student.getStuAge()%> </td> <td> <%=student.getStuXueli()%> </td> <td> <%=student.getStuGender()%> </td> <td> <%=student.getStuScore()%> </td> <td> <%=student.getStuDate()%> </td> <td> <%=student.getStuHobby()%> </td> <td> <%=student.getStuDes()%> </td> <td> <a href="mvc?method=edit&stuId=<%=student.getStuId()%>">編輯</a> <a href="mvc?method=delete&stuId=<%=student.getStuId()%>"onclick="return deleteMethod()">刪除</a> </td> </tr> <%} %> </table> </body> </html> <script src="js/delete.js" type="text/javascript"></script> JSP前端的頁面:編輯的頁面 <%@ page import="com.Model.Student" %> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>學員信息的添加頁面</title> </head> <body> <% Student student=(Student)request.getAttribute("student"); %> <h2 style="color: red" align="center">學員信息的添加頁面</h2> <form action="mvc?method=update" method="post" class="form" onsubmit="return varitore()"> <table> <tr> <td>用戶名:</td> <td> <input type="text" name="stuName" id="stuName" value="<%=student.getStuName()%>" style="background: aqua" placeholder="請輸入用戶名"></br> </td> </tr> <tr> <td>年齡:</td> <td> <input type="text" name="stuAge" id="stuAge"value="<%=student.getStuAge()%>" style="background: aqua" placeholder="請輸入年齡"></br> </td> </tr> <tr> <td>學@歷:</td> <td> <select name="stuXueli" id="stuXueli"> <% if(student.getStuXueli()==0){ %> <option selected value="0">小學</option> <option value="1">初中</option> <option value="2">高中</option> <option value="3">大學</option> <%}else if(student.getStuXueli()==1){%> <option value="0">小學</option> <option selected value="1">初中</option> <option value="2">高中</option> <option value="3">大學</option> <% }else if(student.getStuXueli()==2){ %> <option value="0">小學</option> <option value="1">初中</option> <option selected value="2">高中</option> <option value="3">大學</option> <%}else if(student.getStuXueli()==3){%> <option value="0">小學</option> <option value="1">初中</option> <option value="2">高中</option> <option selected value="3">大學</option> <%} %> </select> </td> </tr><br> <tr> <td>性 別:</td> <td> <% if(student.getStuGender().equals("女")){%> <input type="radio" name="stuGender" checked value="女">女 <input type="radio" name="stuGender" value="男">男</br> <%}else{%> <input type="radio" name="stuGender" value="女">女 <input type="radio" name="stuGender" checked value="男">男</br> <%} %> </td> <tr> <td>成@績:</td> <td> <input type="text" name="stuScore" value="<%=student.getStuScore()%>" id="stuScore" style="background: aqua" placeholder="請輸入成績"><br> </td> </tr> <tr> <td>生 日:</td> <td> <input type="date" name="stuDate" id="stuDate"></br> </td> </tr> <tr> <td>愛@好:</td> <td> <% String[]ars=student.getStuHobby().split("-"); boolean f1=false; boolean f2=false; boolean f3=false; for(int i=0;i<ars.length;i++){ if(ars[i].equals("play")){ f1=true; }else if(ars[i].equals("sing")){ f2=true; }else if(ars[i].equals("sleep")){ f3=true; } } String s1=f1?"checked":""; String s2=f2?"checked":""; String s3=f3?"checked":""; %> <input type="checkbox" <%=s1%> name="stuHobby" value="play">籃球 <input type="checkbox" <%=s2%> name="stuHobby" value="sing">唱歌 <input type="checkbox" <%=s3%> name="stuHobby" value="sleep">睡覺 </td><br> </tr> <tr> <td>文本框:</td> <td> <textarea cols="30" rows="20" name="stuDes" style="background: salmon"><%=student.getStuDes()%></textarea> </td> </tr> <tr> <td colspan="2" align="center"> <input type="submit" value="提交"> <input type="reset" value="重置"> </td> </tr> </table> <!--設置隱藏域屬性--> <input type="hidden" name="stuId" value="<%=student.getStuId()%>"> </form> </body> </html> <script src="js/from.js" type="text/javascript"></script>
JSP前端的頁面: 提示的頁面javascript
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>學員信息提示的頁面</title> </head> <body> <h2 style="color: red">MVC_CRUD</h2> <h3 style="color:red"><a href="add_Stu.jsp">添加學員的信息</a></h3> <h3 style="color:red"><a href="mvc?method=list">學員信息查詢的頁面</a></h3> </body> </html> JSP前端的頁面: 成功的頁面 <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>信息的提示頁面</title> </head> <body> <h2 style="color: red"><%= request.getAttribute("MSG")%></h2> </body> </html>