对三层架构的优化
三层优化
1、加入接口
建议面向接口开发:先实现接口->实现类
--service、dao加入接口
--接口与实现类的命名规范
Service层
接口:interface 起名:IXXxService 所在包名:xxx.service
实现类:implements 起名:XXxServiceImpl 所在包名:xxx.service.Impl
Dao层
接口:interface 起名:IXXxDao 所在包名:xxx.dao
实现类:implements 起名:XXxDaoImpl 所在包名:xxx.dao.Impl
使用接口/实现类 :接口 x = new 实现类 ()
2、DBUtil 通用的数据库帮助类
帮助类所在包名 :XXxutil
方法重构:将多个方法的共同代码提炼出来,单独写在一个方法中,然后引入该方法即可
实例
package org.student.dao;
package org.student.dao; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import org.student.dao.Impl.StudentDaoImpl; import org.student.entity.Student; public interface IStudentDao { //添加学生信息 public boolean AddStudent(Student student); //根据学号删除学生信息 public boolean DeleteStudent(int sno) ; //根据学号修改学生信息:根据sno找到学生,并将学生改为student public boolean UpdateStudent(int sno,Student student); //查询学生是否存在 public boolean isExist(int sno) ; //根据学号查询学生全部信息 public Student Query(int sno); //查询全部学生信息 public List<Student> QueryAll() ; }
package org.student.dao.Impl;
package org.student.dao.Impl; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import org.student.dao.IStudentDao; import org.student.entity.Student; import org.student.util.DBUtil; public class StudentDaoImpl implements IStudentDao{ //添加学生信息 public boolean AddStudent(Student student) { String sql="insert into student(sno,sname,sage,shobby) values(?,?,?,?)" ; Object [] params= {student.getSno(),student.getSname(),student.getSage(),student.getShobby()}; return DBUtil.executeUpdate(sql, params); } //根据学号删除学生信息 public boolean DeleteStudent(int sno) { String sql="delete from student where sno=?" ; Object [] params= {sno}; return DBUtil.executeUpdate(sql, params); } //根据学号修改学生信息:根据sno找到学生,并将学生改为student public boolean UpdateStudent(int sno,Student student) { String sql="update student set sname =?,sage=?,shobby=? where sno =?" ; Object [] params= {student.getSname(),student.getSage(),student.getShobby(),sno}; return DBUtil.executeUpdate(sql, params); } //查询学生是否存在 public boolean isExist(int sno) { return Query(sno)==null? false:true; } //根据学号查询学生全部信息 public Student Query(int sno) { Student student= null; ResultSet rs = null; try { String sql="select * from student where sno =?" ;
Object [] params= {sno};
rs=DBUtil.executeQuery(sql, params); if(rs.next()) { int no=rs.getInt("sno"); String name=rs.getString("sname"); int age=rs.getInt("sage"); String hobby=rs.getString("shobby"); student= new Student(no,name,age,hobby); } }catch(SQLException e) { e.printStackTrace(); }catch(Exception e) { e.printStackTrace(); }finally { try { //先开的后关,后开的先关 if(rs!=null)rs.close(); if(DBUtil.pstmt!=null)DBUtil.pstmt.close(); if(DBUtil.connection !=null)DBUtil.connection.close(); }catch(SQLException e) { e.printStackTrace(); }finally { } } return student; } //查询全部学生信息 public List<Student> QueryAll() { List<Student> students = new ArrayList<>(); Student student= null; ResultSet rs=null; try { String sql="select * from student " ; rs=DBUtil.executeQuery(sql, null); while(rs.next()) { int no=rs.getInt("sno"); String name=rs.getString("sname"); int age=rs.getInt("sage"); String hobby=rs.getString("shobby"); student= new Student(no,name,age,hobby); students.add(student); } }catch(SQLException e) { e.printStackTrace(); }catch(Exception e) { e.printStackTrace(); }finally { try { //先开的后关,后开的先关 if(rs!=null)rs.close(); if(DBUtil.pstmt!=null)DBUtil.pstmt.close(); if(DBUtil.connection !=null)DBUtil.connection.close(); }catch(SQLException e) { e.printStackTrace(); }finally { } } return students; } }
package org.student.entity;
package org.student.entity; public class Student { private int sno; private String sname; private int sage; private String shobby; @Override public String toString() { return "Student [sno=" + sno + ", sname=" + sname + ", sage=" + sage + ", shobby=" + shobby + "]"; } public Student() { } public Student( String sname, int sage, String shobby) { this.sname = sname; this.sage = sage; this.shobby = shobby; } public Student(int sno, String sname, int sage, String shobby) { this.sno = sno; this.sname = sname; this.sage = sage; this.shobby = shobby; } public int getSno() { return sno; } public void setSno(int sno) { this.sno = sno; } public String getSname() { return sname; } public void setSname(String sname) { this.sname = sname; } public int getSage() { return sage; } public void setSage(int sage) { this.sage = sage; } public String getShobby() { return shobby; } public void setShobby(String shobby) { this.shobby = shobby; } }
package org.student.service;
package org.student.service; import java.util.List; import org.student.dao.Impl.StudentDaoImpl; import org.student.entity.Student; public interface IStudentService { public boolean AddStudent(Student student) ; //根据学号进行删除 public boolean DeleteStudent(int sno) ; //根据学号进行修改 public boolean UpdateStudent(int sno,Student student) ; //根据学号查询学生 public Student Query(int sno) ; //查询全部学生 public List<Student> QueryAll(); }
package org.student.service.Impl;
package org.student.service.Impl; import org.student.entity.Student; import org.student.service.IStudentService; import java.util.List; import org.student.dao.*; import org.student.dao.Impl.StudentDaoImpl; public class StudentServiceImpl implements IStudentService{ StudentDaoImpl studentdao= new StudentDaoImpl(); public boolean AddStudent(Student student) { boolean flag=false; if(!studentdao.isExist(student.getSno())) { studentdao.AddStudent(student); flag=true; }else { System.out.println("此人已存在"); } return flag; } //根据学号进行删除 public boolean DeleteStudent(int sno) { boolean flag=false; if(studentdao.isExist(sno)) { studentdao.DeleteStudent(sno); flag=true; }else { System.out.println("此人不存在"); } return flag; } //根据学号进行修改 public boolean UpdateStudent(int sno,Student student) { boolean flag=false; if(studentdao.isExist(sno)) { studentdao.UpdateStudent(sno,student); flag=true; }else { System.out.println("此人不存在"); } return flag; } //根据学号查询学生 public Student Query(int sno) { return studentdao.Query(sno); } //查询全部学生 public List<Student> QueryAll(){ return studentdao.QueryAll(); } }
package org.student.servlet;
AddStudentServlet
package org.student.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.student.entity.Student; import org.student.service.*; import org.student.service.Impl.StudentServiceImpl; public class AddStudentServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); response.setContentType("text/html; charset=utf-8"); int no= Integer.parseInt(request.getParameter("sno")); String name= request.getParameter("sname"); int age= Integer.parseInt(request.getParameter("sage")); String hobby= request.getParameter("shobby"); Student student = new Student(no,name,age,hobby); //接口 x=new 实现类() IStudentService studentservice = new StudentServiceImpl(); boolean result=studentservice.AddStudent(student); //out对象的获取方法 //PrintWriter out = response.getWriter(); //if(result) { // out.println("添加成功"); //}else { // out.println("添加失败"); //} if(!result) { request.setAttribute("message","error"); }else { request.setAttribute("message","noerror"); } request.getRequestDispatcher("QueryAllStudentServlet").forward(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
DeleteStudentServlet
package org.student.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.student.service.*; import org.student.service.Impl.StudentServiceImpl; public class DeleteStudentServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); response.setContentType("text/html; charset=utf-8"); int no= Integer.parseInt(request.getParameter("sno")); IStudentService studentservice = new StudentServiceImpl(); boolean result=studentservice.DeleteStudent(no); //out对象的获取方法 //PrintWriter out = response.getWriter(); //if(result) { // out.println("删除成功"); // response.sendRedirect("QueryAllStudentServlet"); //}else { // out.println("删除失败"); //} if(!result) { request.setAttribute("message","error"); }else { request.setAttribute("message","noerror"); } request.getRequestDispatcher("QueryAllStudentServlet").forward(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
QueryAllStudentServlet
package org.student.servlet; import java.io.IOException; import java.io.PrintWriter; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.student.entity.Student; import org.student.service.*; import org.student.service.Impl.StudentServiceImpl; public class QueryAllStudentServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); response.setContentType("text/html; charset=utf-8"); IStudentService studentservice = new StudentServiceImpl(); List<Student> students=studentservice.QueryAll(); //out对象的获取方法 PrintWriter out = response.getWriter(); request.setAttribute("students", students); request.getRequestDispatcher("index.jsp").forward(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
QueryStudentServlet
package org.student.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.student.entity.Student; import org.student.service.*; import org.student.service.Impl.StudentServiceImpl; public class QueryStudentServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); response.setContentType("text/html; charset=utf-8"); //获取待查询修改人的学号 int no= Integer.parseInt(request.getParameter("sno")); IStudentService studentservice = new StudentServiceImpl(); Student student=studentservice.Query(no); //out对象的获取方法 PrintWriter out = response.getWriter(); out.println(student); request.setAttribute("student", student); request.getRequestDispatcher("studentinfo.jsp").forward(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
UpdateStudentServlet
package org.student.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.student.entity.Student; import org.student.service.*; import org.student.service.Impl.StudentServiceImpl; public class UpdateStudentServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); response.setContentType("text/html; charset=utf-8"); //获取待修改人的学号 int no= Integer.parseInt(request.getParameter("sno")); //获取修改后的内容 String name= request.getParameter("sname"); int age= Integer.parseInt(request.getParameter("sage")); String hobby= request.getParameter("shobby"); //将修改后的内容封装到一个实体类中 Student student = new Student(name,age,hobby); IStudentService studentservice = new StudentServiceImpl(); boolean result=studentservice.UpdateStudent(no,student); //out对象的获取方法 //PrintWriter out = response.getWriter(); //if(result) { // out.println("修改成功"); // response.sendRedirect("QueryAllStudentServlet"); //}else { // out.println("修改失败"); //} if(!result) { request.setAttribute("message","error"); }else { request.setAttribute("message","noerror"); } request.getRequestDispatcher("QueryAllStudentServlet").forward(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
package org.student.util;
package org.student.util; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import org.student.dao.Impl.StudentDaoImpl; import org.student.entity.Student; public class DBUtil { //数据库URL和账号密码 private static final String URL="jdbc:mysql://localhost:3306/login?serverTimezone=UTC&characterEncoding=utf-8"; private static final String UNAME="root"; private static final String UPWD="vayne"; public static PreparedStatement pstmt=null; public static ResultSet rs = null; public static Connection connection=null; //增删改 public static boolean executeUpdate(String sql,Object [] params) { boolean flag = false; try { //a.导入驱动,加载具体的驱动类 Class.forName("com.mysql.cj.jdbc.Driver"); //b.与数据库建立连接 connection = DriverManager.getConnection(URL,UNAME,UPWD); pstmt = connection.prepareStatement(sql); for(int i=0;i<params.length;i++) { pstmt.setObject(i+1, params[i]); } int count=pstmt.executeUpdate();//返回值表示,增删改几条数据 //处理结果 if(count>0) { System.out.println("操作成功!!!"); } }catch(ClassNotFoundException e) { e.printStackTrace(); }catch(SQLException e) { e.printStackTrace(); }catch(Exception e){ e.printStackTrace(); }finally { try { //先开的后关,后开的先关 if(pstmt!=null)pstmt.close(); if(connection !=null)connection.close(); }catch(SQLException e) { e.printStackTrace(); }finally { } } return flag; } //查 public static ResultSet executeQuery(String sql,Object [] params) { try { //a.导入驱动,加载具体的驱动类 Class.forName("com.mysql.cj.jdbc.Driver"); //b.与数据库建立连接 connection = DriverManager.getConnection(URL,UNAME,UPWD); pstmt = connection.prepareStatement(sql); if(params!=null) { for(int i=0;i<params.length;i++) { pstmt.setObject(i+1, params[i]); } } rs = pstmt.executeQuery(); return rs; }catch(ClassNotFoundException e) { e.printStackTrace(); return null; }catch(SQLException e) { e.printStackTrace(); return null; }catch(Exception e){ e.printStackTrace(); return null; } } }
index.jsp
<%@page import="org.student.entity.Student"%> <%@page import="java.util.List"%> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>学生信息列表</title> </head> <body> <% request.setCharacterEncoding("utf-8"); String message=(String)request.getAttribute("message"); if(message!=null){ if(message.equals("error")){ %> <script type="text/javascript"> alert("操作失败"); </script> <% }else if(message.equals("noerror")){ %> <script type="text/javascript"> alert("操作成功"); </script> <% }else{ } } %> <table border="1px"> <tr> <th>学号</th> <th>姓名</th> <th>年龄</th> <th>爱好</th> </tr> <% List <Student> students =(List<Student>) request.getAttribute("students"); for(Student student:students){ %> <tr> <td><%=student.getSno() %></td> <td><%=student.getSname() %></td> <td><%=student.getSage() %></td> <td><%=student.getShobby() %></td> <td><a href ="DeleteStudentServlet?sno=<%=student.getSno() %>">删除</a></td> <td><a href="QueryStudentServlet?sno=<%=student.getSno() %>">查询</a></td> </tr> <% } %> </table> <a href="add.jsp">添加</a> </body> </html>
add.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="AddStudentServlet" method="post"> 学号:<input type="text" name="sno"><br/> 姓名:<input type="text" name="sname"><br/> 年龄:<input type="text" name="sage"><br/> 爱好:<input type="text" name="shobby"><br/> <input type="submit" value="添加"> </form> </body> </html>
studentinfo.jsp
<%@page import="org.student.entity.Student"%> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>学生个人信息</title> </head> <body> <% Student student= (Student)request.getAttribute("student"); %> <form action="UpdateStudentServlet"> 学号:<input type="text" name="sno" value="<%=student.getSno()%>" readonly="readonly"><br/> 姓名:<input type="text" name="sname" value="<%=student.getSname()%>"><br/> 年龄:<input type="text" name="sage" value="<%=student.getSage()%>"><br/> 爱好:<input type="text" name="shobby" value="<%=student.getShobby()%>"><br/> <input type="submit" value="修改"> </form> </body> </html>
对学号为4、5进行删除
对3进行查询和修改
测试完毕,全部实现