三层架构理论:
三层架构和MVC之间的关系:
下面就开始讲案例:
=======================================================================================
案例要实现的功能:用三层架构,在网页上实现学生信息表的增删改查。
数据库:create table student(sno int primary key,sname varchar(20),sage int,saddress varchar(30));
文件结构:
总共:8个java文件,3个JSP文件
源代码按照三层结构分别如下:
第一层:表示层(jsp和servlet):
JSP:1.index.jsp 2.add.jsp 3.studentinfo.jsp
Servlet:4.QueryAllStudentServlet.java 5.AddStudentServlet.java 6.DeleteStudentServlet.java 7.QueryStudentBySnoServlet.java 8.UpdateStudentServlet.java
第二层:业务逻辑层(service层)
9.StudentService.java
第三层:数据访问层(dao层)
Dao:10.StudentDao.java
实体类(不属于三层,但属于MVC中的M层)
Entity:11.Student.java
1.index.jsp
功能:显示所有学生信息表(首页),依赖于QueryAllStudentServlet.java
<%@page import="java.util.List"%>
<%@page import="org.student.entity.Student"%>
<%@page import="org.student.servlet.*"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
学生信息列表
<%
//error:adderror 失败
//否则:1.确实执行了增加 2.直接访问查询全部页面
String error=(String)request.getAttribute("error");//addError
if(error!=null){
if(error.equals("addError")){
out.print("增加失败!");
}else if (error.equals("noaddError")){
out.print("增加成功!");
}//其它就是根本没有执行增加
}
%>
学号
姓名
年龄
地址
操作
查询
<%
//获取request域中的数据
List students=(List)request.getAttribute("students");
for(Student student:students){
%>
<%=student.getSno() %>
<%=student.getSname() %>
<%=student.getSage() %>
<%=student.getSaddress() %>
删除
<%
}
%>
新增
2.add.jsp
功能:增加学生信息页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
增加操作
3.studentinfo.jsp
功能:显示单个学生的信息,也可以在上面对改单个学生信息进行修改。
<%@page import="org.student.entity.Student"%>
<%@page import="org.student.servlet.*"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
显示单个学生信息
<%
Student student=(Student)request.getAttribute("student");
%>
4.QueryAllStudentServlet.java
功能:查询所有学生的信息,完成后显示在index.jsp上。
package org.student.servlet;
import java.io.IOException;
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.StudentService;
/**
* Servlet implementation class QueryAllStudentServlet
*/
public class QueryAllStudentServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
StudentService service=new StudentService();
List students = service.queryAllStudents();
System.out.println(students);
request.setAttribute("students", students);
//因为request域中有数据,因此需要通过请求转发的方式跳转
String error=(String)request.getAttribute("error");//addError
System.out.println(error);
request.getRequestDispatcher("index.jsp").forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
5.AddStudentServlet.java
功能:收到add.jsp传送的增加学生资料后,调用增加学生信息服务增加学生信息,在查询和显示所有学生信息表,并且显示增加成功或者失败。
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.StudentService;
public class AddStudentServlet 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(no,name,age,address);
StudentService studentService=new StudentService();
boolean result = studentService.addStudent(student);
//设置响应编码
response.setCharacterEncoding("utf-8");
response.setContentType("text/html);charset=UTF-8");
PrintWriter out = response.getWriter();
if(!result) {//如果增加失败,给request放入error为“addError”
request.setAttribute("error", "addError");
}else {//否则如果增加成功,给request放入error为“noaddError”
request.setAttribute("error", "noaddError");
}
// response.sendRedirect("QueryAllStudentServlet");
request.getRequestDispatcher("QueryAllStudentServlet").forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
6.DeleteStudentServlet.java
功能:删除学生信息,并重新查询显示最新的所有学生信息表。
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.StudentService;
public class DeleteStudentServlet extends HttpServlet {
public DeleteStudentServlet() {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//删除
request.setCharacterEncoding("utf-8");
//接受前端传来的学好
int no=Integer.parseInt(request.getParameter("sno"));
StudentService service=new StudentService();
boolean result=service.deleteStudentBySno(no);
//设置响应编码
response.setCharacterEncoding("utf-8");
response.setContentType("text/html);charset=UTF-8");
if(result) {
// response.getWriter().println("删除成功doget!");
response.sendRedirect("QueryAllStudentServlet"); //删除后重新查询所有学生
}else {
response.getWriter().println("删除失败!");
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//删除
request.setCharacterEncoding("utf-8");
//接受前端传来的学好
int no=Integer.parseInt(request.getParameter("sno"));
StudentService service=new StudentService();
boolean result=service.deleteStudentBySno(no);
if(result) {
response.getWriter().println("删除成功!");
}else {
response.getWriter().println("删除失败!");
}
}
}
7.QueryStudentBySnoServlet.java
功能:查询某个学生的学生信息,方便查阅或修改。
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.StudentService;
public class QueryStudentBySnoServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
int no=Integer.parseInt(request.getParameter("sno"));
StudentService service=new StudentService();
Student student = service.queryStudentBySno(no);
System.out.println(student);
//将此人的数据通过前台jsp显示
request.setAttribute("student", student); //将查到的学生信息放入request域中
request.getRequestDispatcher("studentinfo.jsp").forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
int no=Integer.parseInt(request.getParameter("sno"));
StudentService service=new StudentService();
Student student = service.queryStudentBySno(no);
// response.setCharacterEncoding("utf-8");
// response.setContentType("text/html);charset=UTF-8");
// PrintWriter out = response.getWriter();
// out.println("No--"+student.getSno()+"")
System.out.println(student);
//将此人的数据通过前台jsp显示
request.setAttribute("student", student); //将查到的学生信息放入request域中
request.getRequestDispatcher("studentinfo.jsp").forward(request, response);
}
}
8.UpdateStudentServlet.java
功能:更新某个学生的学生信息,完成后重新查询显示最新的所有学生信息表。
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.StudentService;
public class UpdateStudentServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doPost(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(no,name,age,address);
StudentService studentService=new StudentService();
boolean result = studentService.updateStudentBySno(no, student);
//设置响应编码
response.setCharacterEncoding("utf-8");
response.setContentType("text/html);charset=UTF-8");
PrintWriter out = response.getWriter();
if(result) {
out.println("更新成功!");
//修改完毕后,重新查询全部学生并显示
response.sendRedirect("QueryAllStudentServlet");
}else {
out.println("更新失败!");
}
}
}
9.StudentService.java
功能:调用dao层的各种数据访问dao,实现增删改查的服务
package org.student.service;
import java.util.List;
import org.student.dao.StudentDao;
import org.student.entity.Student;
//业务逻辑层:逻辑性的增删改查(增:查+增),对dao层进行的组装
public class StudentService {
StudentDao studentDao=new StudentDao();
//添加学生信息
public boolean addStudent(Student student){
if (studentDao.isExist(student.getSno())) {
System.out.println("user have existed");
return false;
}else {
studentDao.addStudent(student);
System.out.println("User add sucessfully!");
return true;
}
}
//根据学号删除学生信息
public boolean deleteStudentBySno(int sno) {
if(studentDao.isExist(sno)) {
return studentDao.deleteStudentBySno(sno);
}
System.out.println("该学号不存在!");
return false;
}
//根据学号修改学生信息
public boolean updateStudentBySno(int sno,Student student){
if(studentDao.isExist(sno)) {
return studentDao.updateStudentBySno(sno,student);
}
System.out.println("该学号不存在!");
return false;
}
//根据学号查询学生信息
public Student queryStudentBySno(int sno) {
return studentDao.queryStudentBySno(sno);
}
//查询所有学生信息
public List queryAllStudents(){
return studentDao.queryAllStudents();
}
}
Dao:10.StudentDao.java
功能:数据访问具体实现:增、删、改、查数据库操作实现。
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.entity.Student;
//数据访问层:原子性的增删改查,不能再分
public class StudentDao {
// private final String URL="jdbd:mysql://localhost:3306/three?serverTimezone=UTC";
// private final String USERNAME="root";
// private final String PASSWORD="prolific";
private static final String URL="jdbc:mysql://localhost:3306/three?serverTimezone=UTC";
private static final String USERNAME="root";
private static final String PASSWORD="prolific";
public boolean isExist(int sno) {//true:此人存在 false:此人不存在。
return queryStudentBySno(sno)==null? false:true;
// if (queryStudentBySno(sno)==null) { //如果是空的,说明此人步存在,false;
// System.out.println("is Exit=false");
// return false;
// }else {
// System.out.println("is Exit=false");
// return true;
// }
}
//增加学生操作
public boolean addStudent(Student student) {//zs 23 xa
Connection connection = null;
PreparedStatement pstmt =null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
connection=DriverManager.getConnection(URL,USERNAME,PASSWORD);
String sql="insert into student values(?,?,?,?)";
pstmt=connection.prepareStatement(sql);
pstmt.setInt(1, student.getSno());
pstmt.setString(2, student.getSname());
pstmt.setInt(3, student.getSage());
pstmt.setString(4, student.getSaddress());
int count=pstmt.executeUpdate();
if (count>0)
return true;
else
return false;
}catch(ClassNotFoundException e) {
e.printStackTrace();
return false;
}catch(SQLException e) {
e.printStackTrace();
return false;
}catch(Exception e) {
e.printStackTrace();
return false;
}finally {
try {
if(connection!=null) connection.close();
if(pstmt!=null) pstmt.close();
}catch(SQLException e) {
e.printStackTrace();
return false;
}
}
}
//根据学号查学生
public Student queryStudentBySno(int sno) {
Connection connection = null;
PreparedStatement pstmt =null;
ResultSet rs=null;
Student student=null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
connection=DriverManager.getConnection(URL,USERNAME,PASSWORD);
String sql="select * from student where sno=?";
pstmt=connection.prepareStatement(sql);
pstmt.setInt(1, sno);
rs=pstmt.executeQuery();
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(ClassNotFoundException e) {
e.printStackTrace();
return null;
}catch(SQLException e) {
e.printStackTrace();
return null;
}catch(Exception e) {
e.printStackTrace();
return null;
}finally {
try {
if(rs!=null) rs.close();
if(connection!=null) connection.close();
if(pstmt!=null) pstmt.close();
}catch(SQLException e) {
e.printStackTrace();
}
}
}
//查询全部学生
public List queryAllStudents() {
List students=new ArrayList<>();
Connection connection = null;
PreparedStatement pstmt =null;
ResultSet rs=null;
Student student=null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
connection=DriverManager.getConnection(URL,USERNAME,PASSWORD);
String sql="select * from student";
pstmt=connection.prepareStatement(sql);
rs=pstmt.executeQuery();
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(ClassNotFoundException e) {
e.printStackTrace();
return null;
}catch(SQLException e) {
e.printStackTrace();
return null;
}catch(Exception e) {
e.printStackTrace();
return null;
}finally {
try {
if(rs!=null) rs.close();
if(connection!=null) connection.close();
if(pstmt!=null) pstmt.close();
}catch(SQLException e) {
e.printStackTrace();
}
}
}
//根据学号 删除学生
public boolean deleteStudentBySno(int sno) {
Connection connection = null;
PreparedStatement pstmt =null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
connection=DriverManager.getConnection(URL,USERNAME,PASSWORD);
String sql="delete from student where sno=?";
pstmt=connection.prepareStatement(sql);
pstmt.setInt(1, sno);
int count=pstmt.executeUpdate();
if (count>0)
return true;
else
return false;
}catch(ClassNotFoundException e) {
e.printStackTrace();
return false;
}catch(SQLException e) {
e.printStackTrace();
return false;
}catch(Exception e) {
e.printStackTrace();
return false;
}finally {
try {
if(connection!=null) connection.close();
if(pstmt!=null) pstmt.close();
}catch(SQLException e) {
e.printStackTrace();
return false;
}
}
}
//根据学好修改学生:根据sno知道待修改的人,在把这个人修改成student
public boolean updateStudentBySno(int sno,Student student) {
Connection connection = null;
PreparedStatement pstmt =null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
connection=DriverManager.getConnection(URL,USERNAME,PASSWORD);
String sql="update student set sname=?,sage=?,saddress=? where sno=?";
pstmt=connection.prepareStatement(sql);
pstmt.setString(1, student.getSname());
pstmt.setInt(2, student.getSage());
pstmt.setString(3, student.getSaddress());
pstmt.setInt(4, sno);
int count=pstmt.executeUpdate();
if (count>0)
return true;
else
return false;
}catch(ClassNotFoundException e) {
e.printStackTrace();
return false;
}catch(SQLException e) {
e.printStackTrace();
return false;
}catch(Exception e) {
e.printStackTrace();
return false;
}finally {
try {
if(connection!=null) connection.close();
if(pstmt!=null) pstmt.close();
}catch(SQLException e) {
e.printStackTrace();
return false;
}
}
}
}
Entity:11.Student.java
功能:封装数据的JavaBean,学生信息的封装
package org.student.entity;
public class Student {
private int sno;
private String sname;
private int sage;
private String saddress;
public Student() {
}
public Student(String sname, int sage, String saddress) {
this.sname = sname;
this.sage = sage;
this.saddress = saddress;
}
public Student(int sno, String sname, int sage, String saddress) {
this.sno = sno;
this.sname = sname;
this.sage = sage;
this.saddress = saddress;
}
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 getSaddress() {
return saddress;
}
public void setSadress(String saddress) {
this.saddress = saddress;
}
public String toString() {
return this.getSno()+"-"+this.getSname()+"-"+this.getSage()+"-"+this.getSaddress();
}
}
运行测试:
运行执行:QueryAllStudentServlet
http://localhost:8888/StudentManage/QueryAllStudentServlet
结果显示:
功能实现正常!