前言:
1 该程序使用动态web项目
2 该程序使用SQL server需导入对应包( 具体可看前篇----JDBC的使用)
3 三层架构思想:
①表示层
前台:jsp/html等 作为前台与用户交互
后台:用于控制跳转,调用业务逻辑层
②业务逻辑层
将数据访问层进行组装
给表示层调用
③数据访问层
所有小功能和函数建立
与数据库相连 以dao命名
4 该程序体现面向接口开发:先接口-再实现类(此为规范!!)
当实体类需要实例时
运用:接口=new 实例
service、dao加入接口
命名规范:
接口:IXXX 例:IStudentDao
实现类:XXXImpl 例:StudentDaoImpl
5 DBUtil作为通用数据库工具类,实现通用调用数据库方法
6 该程序使用tomcat8.5
以下是示例目录
以下是代码实例
IStudentDao(作为dao的接口 将方法写出但不做声明)
package dao; import java.util.List; import entity.Student; public interface IStudentDao { public boolean isExist(int sno); public boolean AddStudent(Student student); public List<Student> queryAll(); public boolean updateStudentBySno(int sno,Student student); public Student queryStudentBysno(int sno); public boolean deleteStudentBySno(int sno); }
StudentDaoImpl(实现接口方法-增、删、改、查单人/查所有)
##用DBUtil封装方法 达到减少代码量目的
package daoImpl; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import dao.IStudentDao; import entity.Student; import util.DBUtil; /* * 数据访问层 * 与数据库交互 */ public class StudentDaoImpl implements IStudentDao { /* * 判断学号是否存在 * 返回学号是否存在 */ public boolean isExist(int sno) { return queryStudentBysno(sno)==null?false:true; } /* * 增加学生信息 * 返回是否成功 */ public boolean AddStudent(Student student) { String sql="insert into student values(?,?,?,?)"; Object[] params= {student.getSno(),student.getSname(),student.getAge(),student.getAge(),student.getAddress()}; return DBUtil.executeUpdate(sql, params); } /* * 根据学号删人 * 返回是否成功 */ public boolean deleteStudentBySno(int sno) { String sql="delete student where sno=?"; Object[] params= {sno}; return DBUtil.executeUpdate(sql, params); } /* * 根据学号sno修改数据student * 返回是否成功 */ public boolean updateStudentBySno(int sno,Student student) { String sql="update student set sname=?,sage=?,saddress=? where sno=?"; Object[] params= {student.getSname(),student.getAge(),student.getAddress(),sno}; return DBUtil.executeUpdate(sql, params); } /* * 查询全部学生 * 返回学生集合 */ public List<Student> queryAll() { Student student=null; PreparedStatement pst =null; ResultSet rs =null; List<Student> students=new ArrayList<Student>(); 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 address=rs.getString("saddress"); student=new Student(no,name,age,address); students.add(student); } return students; } catch (SQLException e) { e.printStackTrace(); return null; } catch (Exception e) { e.printStackTrace(); return null; }finally { try { if(rs!=null) rs.close(); if(pst!=null) pst.close(); if(DBUtil.connection!=null) DBUtil.connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } /* * 根据学号查询学生 * 返回查询学生类 */ public Student queryStudentBysno(int sno) { Student student=null; PreparedStatement pst =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 address=rs.getString("saddress"); student=new Student(no,name,age,address); } return student; } catch (SQLException e) { e.printStackTrace(); return null; } catch (Exception e) { e.printStackTrace(); return null; }finally { DBUtil.closeAll(rs, pst, DBUtil.connection); } } }
DBUtil减少代码冗余-并实现 数据库通用工具类思想
package util; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; //通用的数据库操作方法 public class DBUtil { //sql数据库连接字符串 private static final String URL="jdbc:sqlserver://localhost:1433;databasename=javatest"; //sql用户名 和密码 用作连接用 private static final String USERNAME="sa"; private static final String PWD="cc123nice"; public static Connection connection=null; public static PreparedStatement pst =null; public static ResultSet rs =null; /* * 得到PreparedStatement减少代码冗余 */ public static PreparedStatement getPreparedStatement(String sql,Object[] params) { //导入驱动,加载具体驱动类 try { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); //与数据库建立链接 connection = DriverManager.getConnection(URL, USERNAME, PWD); pst=connection.prepareStatement(sql); if(params!=null) { for(int i=0;i<params.length;i++){ pst.setObject(i+1,params[i]); } } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } return pst; } /* * 最后关闭所有 */ public static void closeAll(ResultSet rs,Statement stmt,Connection connection) { try { if(rs!=null) rs.close(); if(stmt!=null) stmt.close(); if(connection!=null) connection.close(); } catch (SQLException e) { e.printStackTrace(); } } /* * 通用的增删改 通过传入的sql和obj数组确认语句 */ public static boolean executeUpdate(String sql,Object[] params) { try { int count = getPreparedStatement(sql,params).executeUpdate(); if(count>0) return true; else return false; } catch (SQLException e) { e.printStackTrace(); return false; } catch (Exception e) { e.printStackTrace(); return false; }finally { closeAll(null, pst, connection); } } /* * 通用的查询(只能返回到ResultSet)之后必须与具体类型耦合 */ public static ResultSet executeQuery(String sql,Object[] params) { try { rs= getPreparedStatement(sql,params).executeQuery(); return rs; } catch (SQLException e) { e.printStackTrace(); return null; } catch (Exception e) { e.printStackTrace(); return null; } } }
IStudentService(作为service的接口 将方法写出但不做声明)
package service; import java.util.List; import entity.Student; public interface IStudentService { public boolean addStudent(Student student); //删 public boolean deleteStudentBySno(int sno); //改 public boolean updateStudentBySno(int sno,Student student); //根据学号查 public Student queryStudentBysno(int sno) ; //查询所有 public List<Student> queryAll(); }
StudentServiceImpl实现接口IStudentService方法实现
主要对dao实例内的方法进行封装
package serviceImpl; import java.util.List; import dao.IStudentDao; import daoImpl.StudentDaoImpl; import entity.Student; import service.IStudentService; /* * 业务逻辑层 对dao层进行组装 逻辑性增删改查(增删改==查+操作) */ public class StudentServiceImpl implements IStudentService{ IStudentDao std=new StudentDaoImpl(); //增 public boolean addStudent(Student student) { if(!std.isExist(student.getSno())){ return std.AddStudent(student); }else return false; } //删 public boolean deleteStudentBySno(int sno) { if(std.isExist(sno)){ return std.deleteStudentBySno(sno); }else return false; } //改 public boolean updateStudentBySno(int sno,Student student) { if(std.isExist(sno)){ return std.updateStudentBySno(sno, student); }else return false; } //根据学号查 public Student queryStudentBysno(int sno) { return std.queryStudentBysno(sno); } //查询所有 public List<Student> queryAll(){ return std.queryAll(); } }
MyServerlet包中存放对各个方法的servlet(实现1对1的情况)将表示层的信息处理、向下-处理层传递/向上-表示层传递
AddServlet实现‘增加’的表示层后台
package MyServerlet; import java.io.IOException; 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 entity.Student; import service.IStudentService; import serviceImpl.StudentServiceImpl; /* * serverlet--增加 */ @WebServlet("/AddServerlet") public class AddServlet extends HttpServlet { private static final long serialVersionUID = 1204432039484958110L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { int sno =Integer.parseInt( request.getParameter("sno")); String name = request.getParameter("sname"); int age = Integer.parseInt(request.getParameter("sage")); String address = request.getParameter("saddress"); Student student =new Student(sno,name,age,address); IStudentService studentService = new StudentServiceImpl(); boolean res = studentService.addStudent(student); request.setCharacterEncoding("utf-8"); //给request增加标识符 if(!res) request.setAttribute("res", "增加失败"); else request.setAttribute("res", "增加成功"); }catch(Exception e){ request.setAttribute("res", "数据有误增加失败"); } request.getRequestDispatcher("QueryAllServlet").forward(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
DeleteServlet实现‘删除’的表示层后台
package MyServerlet; import java.io.IOException; 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 service.IStudentService; import serviceImpl.StudentServiceImpl; @WebServlet("/DeleteServerlet") public class DeleteServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //接受学号 int sno = Integer.parseInt(request.getParameter("sno")); IStudentService service = new StudentServiceImpl(); boolean res = service.deleteStudentBySno(sno); response.setContentType("text/html; charset=utf-8"); if(!res) request.setAttribute("res", "删除失败"); else request.setAttribute("res", "删除成功"); request.getRequestDispatcher("QueryAllServlet").forward(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
QueryAllServlet实现‘查找所有’的表示层后台
package MyServerlet; import java.io.IOException; 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 service.IStudentService; import serviceImpl.StudentServiceImpl; @WebServlet("/DeleteServerlet") public class DeleteServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //接受学号 int sno = Integer.parseInt(request.getParameter("sno")); IStudentService service = new StudentServiceImpl(); boolean res = service.deleteStudentBySno(sno); response.setContentType("text/html; charset=utf-8"); if(!res) request.setAttribute("res", "删除失败"); else request.setAttribute("res", "删除成功"); request.getRequestDispatcher("QueryAllServlet").forward(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
QuerySnoServlet实现‘通过学号查找’的表示层后台
此处重定向到studentinfo.jsp 以下进行解析
package MyServerlet; import java.io.IOException; 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 entity.Student; import service.IStudentService; import serviceImpl.StudentServiceImpl; @WebServlet("/QuerySnoServerlet") public class QuerySnoServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { int no = Integer.parseInt(request.getParameter("sno")); IStudentService service = new StudentServiceImpl(); Student student = service.queryStudentBysno(no); request.setAttribute("student", student); request.getRequestDispatcher("studentinfo.jsp").forward(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
UpdateServlet实现‘修改’的表示层后台
package MyServerlet; import java.io.IOException; 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 entity.Student; import service.IStudentService; import serviceImpl.StudentServiceImpl; @WebServlet("/UpdateServlet") public class UpdateServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //处理获取数据编码 request.setCharacterEncoding("utf-8"); //获取待修改学生的学号 int no = Integer.parseInt(request.getParameter("sno")); //修改后内容 String name = request.getParameter("sname"); int age = Integer.parseInt(request.getParameter("sage")); String address = request.getParameter("saddress"); Student student=new Student(name,age,address); IStudentService service = new StudentServiceImpl(); boolean res = service.updateStudentBySno(no, student); //处理相应编码 response.setContentType("text/html; charset=utf-8"); if(!res) request.setAttribute("res", "修改失败"); else request.setAttribute("res", "修改成功"); request.getRequestDispatcher("QueryAllServlet").forward(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
以下为表示层前台
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="AddServerlet"> 学号:<input type="text" name="sno"/><br/> 姓名:<input type="text" name="sname"/><br/> 年龄:<input type="text" name="sage"/><br/> 地址:<input type="text" name="saddress"/><br/> <input type="submit" value="新增"/><br/> </form> </body> </html>
index.jsp 以表单显示所有学生基本信息
实现学号超链接更多信息
实现新增信息
实现删除信息
<%@page import="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> <% String res=(String)request.getAttribute("res"); if(res!=null){ out.print(res); } %> <!-- 设置表格边框 --> <table border="1PX"> <!-- 设置标题 --> <tr> <th>学号</th> <th>姓名</th> <th>年龄</th> <th>操作</th> </tr> <% //获取request域中的数据 List<Student> students=( List<Student> ) request.getAttribute("students"); for(Student student:students){ %> <tr> <td><a href="QuerySnoServerlet?sno=<%=student.getSno() %>"><%=student.getSno() %></a></td> <td><%=student.getSname() %></td> <td><%=student.getAge() %></td> <td><a href="DeleteServerlet?sno=<%=student.getSno() %>">删除</a></td> </tr> <% } %> </table> <a href="add.jsp">增加</a> </body> </html>
studentinfo.jsp 以表单形式显示具体信息
可以直接填写表单进行修改
<%@page import="entity.Student"%> <%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Insert title here</title> </head> <body> <% Student student=(Student)request.getAttribute("student"); %> <!-- 表单显示信息 --> <form action="UpdateServlet"> 学号:<input type="text" name="sno" value=<%=student.getSno() %>><br> 姓名:<input type="text" name="sname" value=<%=student.getSname() %>><br> 年龄:<input type="text" name="sage" value=<%=student.getAge() %>><br> 地址:<input type="text" name="saddress" value=<%=student.getAddress() %>><br> <input type="submit" value="修改"> </form> <a href="QueryAllServlet">返回</a> </body> </html>
成品示例(需要链接中不显示具体信息,再提交表单处增加 method='post')
进入界面显示所有学生信息
点击学号1查看具体信息
直接修改数据