这是对上一个三层架构定义及代码(二)后面例子的完善,
之前例子只有增加功能,现在一步步完善全部功能,但是代码已经全部写完了,只能一步步整理整个过程。
目录
项目目录图示
一. 目的及实现情况
设计一个对学生的增删改查
1.1. index.jsp
1.2. add.jsp
1.3. studentInfo.jsp
1.4. 基本流程
index.jsp 展示基础信息,点击删除按钮直接删除对应学号的信息,并自动刷新;
点击新增链接跳转到add.jsp,增加后返回index.jsp,并提示增加成功与否;
点击学号超链接,进入对应学号的全部信息页面studentInfo.jsp,可以修改除学号之外的所有,修改后返回首页。
二. 项目接口与实现类规范
2.1. 基本规范
- 建议面向接口开发:先接口-再实现类
- 加入接口的地方:ervice、dao加入接口
接口起名形式 | 例如 | 位于的包名 | 对应类起名形式 | 例如 | 位于的包名 |
---|---|---|---|---|---|
I实体类Service(Service) | IStudentService | xxx.service | 实体类ServiceImpl | StudentServiceImpl | xx.dao |
I实体类Dao(Dao) | IStudentDao | xxx.service.impl | 实体类DaoImpl | StudentDaoImpl | xx.dao.impl |
- 代码规范:
以后使用接口/实现类时,推荐写法:
接口 x = new 实现类()
IStudentDao studentDao = new StudentDaoImpl();
2.2. IStudentDao.java接口
Dao层与Service层都对应接口
package org.student.dao;
import java.util.List;
import org.student.entity.Student;
public interface IStudentDao {
//删除学生,根据学号删除学生
public boolean deleteStudentBysno(int sno) ;
// 修改学生,根据学号,修改学生信息
public boolean updateStudentBysno(int sno,Student student) ;
// 添加学生
public boolean addStudent(Student student) ;
// 通过学号,返回学生是否存在
public boolean isExist(int sno) ;
// 查询全部学生,返回的是一个集合
public List<Student> queryAllStudents() ;
// 根据姓名查询
// 根据年龄查
// 通过学号,返回学生
public Student queryStudentBysno(int sno) ;
}
三. IStudentService.java接口
package org.student.service;
import java.util.List;
import org.student.entity.Student;
public interface IStudentService {
// 根据学号查学生
public Student queryStudentBySno(int sno) ;
// 查询全部学生
public List<Student> queryAllStudents() ;
// 改
public boolean updeteStudentBySno(int sno,Student student) ;
// 删除
public boolean deleteStudentBySno(int sno) ;
// 增加学生
public boolean addstudent(Student student) ;
}
四. Servlet类实现
- 每一个功能,对应一个servlet
- 现在有增删改查(查全部,查一个),所以对应5个servlet
- AddStudentServlet
- DeleteStudentServlet
- UpdateStudentServlet
- QueryAllStudentServlet
- QueryStudentBySnoServlet
五. Servlet类功能验证(不需前端)
- 页面的跳转都会跳转到对应的 /xxxServlet,直接在后面写上对应的传入数据,通过打印,验证功能的实现
? = &
- http://localhost:8080/ThreeTierSample/
AddStudentServlet
- http://localhost:8080/ThreeTierSample/
DeleteStudentServlet?sno=3
- http://localhost:8080/ThreeTierSample/
UpdateStudentServlet?sno=2&sname=李四&sage=55&saddress=中国
- http://localhost:8080/ThreeTierSample/
QueryAllStudentServlet
- http://localhost:8080/ThreeTierSample/
QueryStudentBySnoServlet?sno=1
六. 流程解释
- index.jsp总是在QueryAllStudentServlet执行后,在获取数据展示,所以应该先执行QueryAllStudentServlet,在跳转到index.jsp。
- 解决:在启动时先执行QueryAllStudentServlet,修改Web.xml
<welcome-file>QueryAllStudentServlet</welcome-file>
- QueryAllStudentServlet在最后通过请求转发到index.jsp页面
- 许多Servlet在最后都需要跳转到QueryAllStudentServlet,重新执行查询全部,传入值,在跳转到index.jsp
- 对于判断是否增加成功,删除成功,修改成功;就针对是否增加成功来说:分三种情况,1.直接访问首页 2.删除成功返回首页 3.删除失败返回首页,所以在DeleteStudentServlet中要设置标志位,对于删除成功,失败设置不同标志位:
if (!result) { //增加失败
// 加入标识符
request.setAttribute("error", "addError");
}else {
request.setAttribute("error", "noAddError");
}
request.getRequestDispatcher("QueryAllStudentServlet").forward(request, response);
在首页获取代码:
<%
// 1.增加失败 2.增加成功 3.直接访问查询全部页面
String error = (String)request.getAttribute("error");
// 在不是直接访问查询全部页面情况下 进入判断,否则不提示
if(error != null){
if(error.equals("addError")){ //增加失败
out.print("增加失败");
}else{
out.print("增加成功");
}
}
%>
七. 具体代码
7.1. index.jsp
<body>
<%
// 1.增加失败 2.增加成功 3.直接访问查询全部页面
String error = (String)request.getAttribute("error");
// 在不是直接访问查询全部页面情况下 进入判断,否则不提示
if(error != null){
if(error.equals("addError")){ //增加失败
out.print("增加失败");
}else{
out.print("增加成功");
}
}
%>
<table border = "1px">
<tr>
<th>学号</th>
<th>姓名</th>
<th>年龄</th>
<th>操作</th>
</tr>
<%
// 从QueryAllStudentServlet跳转过来的(在xml里改过了),
//需要先查询,再显示数据,因为这里要获取数据
// 获取request域里的数据,Object类型转换
List<Student> students = (List<Student>) request.getAttribute("students");
for(Student student : students ){
%>
<tr>
<!-- 学号跳转查询此人信息 -->
<th><a href="QueryStudentBySnoServlet?sno=<%=student.getSno() %>"><%=student.getSno() %></a></th>
<th><%=student.getSname() %></th>
<th><%=student.getSage() %></th>
<th><a href="DeleteStudentServlet?sno=<%=student.getSno() %>">删除</a></th>
</tr>
<%
}
%>
</table>
<a href="add.jsp">新增</a>
</body>
7.2. studentInfo.jsp
<body>
<%
Student student = (Student) request.getAttribute("student");
%>
<!-- 通过表单展示,易于修改 -->
<form action="UpdateStudentServlet">
<!-- readonly 不可改 -->
学号:<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="saddress" value="<%=student.getSaddress()%>"/><br/>
<input type="submit" value="修改"/>
<a href="QueryAllStudentServlet">返回</a>
</form>
</body>
7.3. add.jsp
<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 = "saddress" /> <br/>
<input type = "submit" value="新增" /> <br/>
</form>
</body>
7.4. AddStudentServlet.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.IStudentService;
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"); //请求编码
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);
// 接口 X = new 实现类();
IStudentService studentService = new StudentServiceImpl();
boolean result = studentService.addstudent(student);
// 1.先设置响应编码
response.setContentType("text/html; charset=UTF-8");
response.setCharacterEncoding("utf-8");
// 2. 再响应 ----------注意1,2先后顺序
PrintWriter out = response.getWriter(); //响应对象
if (!result) { //增加失败
// 加入标识符
request.setAttribute("error", "addError");
}else {
request.setAttribute("error", "noAddError");
}
request.getRequestDispatcher("QueryAllStudentServlet").forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
7.5. 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.IStudentService;
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");
// 接收传过来的学号
int sno = Integer.parseInt(request.getParameter("sno"));
IStudentService service = new StudentServiceImpl();
boolean result = service.deleteStudentBySno(sno);
// 1.先设置响应编码
response.setContentType("text/html; charset=UTF-8");
response.setCharacterEncoding("utf-8");
// 2. 再响应 ----------注意1,2先后顺序
PrintWriter out = response.getWriter(); //响应对象
if (result) {
// response.getWriter().println("删除成功"); //跳转太快,没有用
response.sendRedirect("QueryAllStudentServlet"); //重新查询全部
}else {
response.getWriter().println("删除失败");
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
7.6. QueryAllStudentServlet .java
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.IStudentService;
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");
IStudentService service = new StudentServiceImpl();
List<Student> students = service.queryAllStudents();
System.out.println(students);
// 存入数据
request.setAttribute("students", students);
// 因为request中有数据,通过请求转发(重定向丢失request),跳转到index.jsp显示数据
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);
}
}
7.7. QueryStudentBySnoServlet .java
package org.student.servlet;
import java.io.IOException;
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.IStudentService;
import org.student.service.impl.StudentServiceImpl;
public class QueryStudentBySnoServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
int sno = Integer.parseInt(request.getParameter("sno"));
IStudentService service = new StudentServiceImpl();
Student student = service.queryStudentBySno(sno);
System.out.println(student);
// 将此人的数据通过前台jsp显示 ---studentInfo.jsp
request.setAttribute("student", student); //放信息
// 如果request域没有数据,使用重定向跳转respose.sendRedirect()
// 如果request域有数据(request.setArrribute()),使用请求转发跳转
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);
}
}
7.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.IStudentService;
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");
// 接收传过来的学号
int sno = Integer.parseInt(request.getParameter("sno"));
String sname = request.getParameter("sname");
int sage = Integer.parseInt(request.getParameter("sage"));
String saddress = request.getParameter("saddress");
// 封装到javaBean
Student student = new Student(sname, sage, saddress);
IStudentService service = new StudentServiceImpl();
boolean result = service.updeteStudentBySno(sno, student);
// 1.先设置响应编码
response.setContentType("text/html; charset=UTF-8");
response.setCharacterEncoding("utf-8");
// 2. 再响应 ----------注意1,2先后顺序
PrintWriter out = response.getWriter(); //响应对象
if (result) {
// response.getWriter().println("修改成功");
response.sendRedirect("QueryAllStudentServlet"); //重新查询全部
}else {
response.getWriter().println("修改失败");
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
7.9. StudentDaoImpl .java
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.util.LinkedList;
import java.util.List;
import org.student.dao.IStudentDao;
import org.student.entity.Student;
//数据访问层 :原子性的增删改查
public class StudentDaoImpl implements IStudentDao{
private final String URL = "jdbc:mysql://localhost:3306/mvc";
private final String USERNAME = "root";
private final String PASSWORD = "root";
//删除学生,根据学号删除学生
public boolean deleteStudentBysno(int sno) {
PreparedStatement pstmt = null;
Connection connection = null;
try {
Class.forName("com.mysql.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 (pstmt != null) pstmt.close();
if (connection != null) connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
// 修改学生,根据学号,修改学生信息
public boolean updateStudentBysno(int sno,Student student) {
PreparedStatement pstmt = null;
Connection connection = null;
try {
Class.forName("com.mysql.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 (pstmt != null) pstmt.close();
if (connection != null) connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
// 添加学生
public boolean addStudent(Student student) { // zs 23 xm
PreparedStatement pstmt = null;
Connection connection = null;
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
String sql = "insert into student(sno,sname,sage,saddress) values(?,?,?,?)";
pstmt = connection.prepareStatement(sql);
pstmt.setInt(1, student.getSno());
pstmt.setString(2, student.getSname());
pstmt.setInt(3, student.getSno());
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 (pstmt != null) pstmt.close();
if (connection != null) connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
// 通过学号,返回学生是否存在
public boolean isExist(int sno) { // true:存在 false:不存在
return queryStudentBysno(sno) == null ? false : true;
}
// 查询全部学生,返回的是一个集合
public List<Student> queryAllStudents() {
List<Student> students = new LinkedList<Student>();
Student student = null;
Connection connection = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.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 (pstmt != null) pstmt.close();
if (connection != null) connection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
// 根据姓名查询
// 根据年龄查
// 通过学号,返回学生
public Student queryStudentBysno(int sno) {
Student student = null;
Connection connection = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.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 (pstmt != null) pstmt.close();
if (connection != null) connection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
7.10. StudentServiceImpl .java
package org.student.service.impl;
import java.util.List;
import org.student.dao.IStudentDao;
import org.student.dao.impl.StudentDaoImpl;
import org.student.entity.Student;
import org.student.service.IStudentService;
// 业务逻辑层:逻辑性增删改查( 增:查+增),对dao层进行组装
public class StudentServiceImpl implements IStudentService{
IStudentDao studentDao = new StudentDaoImpl();
// 根据学号查学生
public Student queryStudentBySno(int sno) {
return studentDao.queryStudentBysno(sno);
}
// 查询全部学生
public List<Student> queryAllStudents() {
return studentDao.queryAllStudents();
}
// 改
public boolean updeteStudentBySno(int sno,Student student) {
if (studentDao.isExist(sno)) { //存在
studentDao.updateStudentBysno(sno, student); //改
return true; // 返回true
}
return false;
}
// 删除
public boolean deleteStudentBySno(int sno) {
if (studentDao.isExist(sno)) { //存在
studentDao.deleteStudentBysno(sno); //删
return true; // 返回true
}
return false;
}
// 增加学生
public boolean addstudent(Student student) {
if (!studentDao.isExist(student.getSno())) { //不存在
studentDao.addStudent(student); // 进行添加
return true;
}else {
System.out.println("此人已经存在");
return false;
}
}
}
7.11. Student .java
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) {
super();
this.sname = sname;
this.sage = sage;
this.saddress = saddress;
}
public Student(int sno, String sname, int sage, String saddress) {
super();
this.sno = sno;
this.sname = sname;
this.sage = sage;
this.saddress = saddress;
}
@Override
public String toString() {
return "Student [sno=" + sno + ", sname=" + sname + ", sage=" + sage + ", 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 setSaddress(String saddress) {
this.saddress = saddress;
}
}
来源:CSDN
作者:葫芦娃救蛇精
链接:https://blog.csdn.net/qq_43542795/article/details/104055036