[原创]java WEB学习笔记19:初识MVC 设计模式:查询,删除 练习(理解思想),小结 ,问题

时间:2023-03-09 07:19:46
[原创]java WEB学习笔记19:初识MVC 设计模式:查询,删除 练习(理解思想),小结 ,问题

本博客为原创:综合 尚硅谷(http://www.atguigu.com)的系统教程(深表感谢)和 网络上的现有资源(博客,文档,图书等),资源的出处我会标明

本博客的目的:①总结自己的学习过程,相当于学习笔记 ②将自己的经验分享给大家,相互学习,互相交流,不可商用

内容难免出现问题,欢迎指正,交流,探讨,可以留言,也可以通过以下方式联系。

本人互联网技术爱好者,互联网技术发烧友

微博:伊直都在0221

QQ:951226918

-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

1.在上一学习笔记中,了解了MVC设计的思想,这一学习笔记,主要手动写一个MVC的查询程序,比较糙,重理解思想

2.需求:通过index.jsp 页面发过请求,查询学生的信息,将学生的信息输出到des.jsp页面上;可以删除学生的信息。

3.代码结构

  1)index.jsp  : 一个查询的超链接页面;

  2)des.jps     :  显示查询的页面;

  3)success.jsp :删除成功后跳转的页面

  4)ListAllStudentsServlet.java : 负责处理index 页面请求的servlet,同时与dao交互;

  5)DeletStudentServlet.java   :通过传入的flowId 进行删除;

  6)StudentDao.java : 定义方法getA() 用于与数据库交互,查询数据 ,返回结果;deleteByFlowId(int flowId)方法,按照flowId删除相应的学生信息;

  7)Student.java  :bean  同数据库表的字段一致,get set方法,带参,不带餐构造器,用于检查的 toString 方法;

4.具体代码

  1)index.jsp

 <%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>index</title>
</head>
<body>
<a href="listAllStudents">List All Students</a> </body>
</html>

  

  2)des.jsp

 <%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="java.util.List"%>
<%@ page import="com.jason.testMVC.Student"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>des</title>
</head>
<body>
<%
List<Student> stus = (List<Student>) request
.getAttribute("students"); if (stus == null) {
System.out.println("stus is null");
} else {
%>
<table border="1" cellpadding="10" cellspacing="0">
<tr>
<th>FlowId</th>
<th>Type</th>
<th>IdCard</th>
<th>ExamCard</th>
<th>StudentName</th>
<th>Location</th>
<th>Grade</th>
<th>Delete</th>
</tr>
<%
for (Student stu : stus) {
%>
<tr>
<td><%=stu.getExamCard()%></td>
<td><%=stu.getType()%></td>
<td><%=stu.getIdCard()%></td>
<td><%=stu.getExamCard()%></td>
<td><%=stu.getStudentName()%></td>
<td><%=stu.getLocation()%></td>
<td><%=stu.getGrade()%></td>
<td><a href="deletStudent?flowId=<%=stu.getFlowId() %>"/>Delete</td> //通过这个种方式,向servlet传入flowId参数
</tr>
<%
}
}
%>
</table> </body>
</html>

  3)success.jsp

 <%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body> <h1>删除成功</h1>
<a href="listAllStudents">List All Students</a> </body>
</html>

  4)ListAllStudentsServlet.java

 package com.jason.testMVC;

 import java.io.IOException;
import java.util.List; import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; /**
* Servlet implementation class ListAllStudentsServlet
*/
@WebServlet("/listAllStudents")
public class ListAllStudentsServlet extends HttpServlet {
private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { StudentDao studentDao = new StudentDao();
List<Student> students = studentDao.getAll(); request.setAttribute("students", students); request.getRequestDispatcher("/students.jsp").forward(request, response);
} }

  

  5)DeletStudentServlet.java

 package com.jason.testMVC;

 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 com.sun.org.apache.xalan.internal.xsltc.compiler.sym; /**
* Servlet implementation class DeletStudentServlet
*/ @WebServlet("/deletStudent")
public class DeletStudentServlet extends HttpServlet {
private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String flowIdStr = request.getParameter("flowId");
// int flowId = Integer.parseInt(flowIdStr);
// System.out.println(flowIdStr); StudentDao studentDao = new StudentDao();
boolean flage = studentDao.deleteByFlowId(Integer.parseInt(flowIdStr)); if(flage){
request.getRequestDispatcher("/success.jsp").forward(request, response);
}else{
System.out.println("删除失败");
} } }

  6)StudentDao.java

 package com.jason.testMVC;

 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; public class StudentDao { public List<Student> getAll() { List<Student> students = new ArrayList<Student>();
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null; try { String driverClass = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://127.0.0.1:3306/atguigu";
String user = "root";
String password = "zhangzhen";
// 加载驱动类
Class.forName(driverClass);
connection = DriverManager.getConnection(url, user, password); String sql = "SELECT * FROM student"; preparedStatement = connection.prepareStatement(sql);
resultSet = preparedStatement.executeQuery(); while (resultSet.next()) {
int FlowId = resultSet.getInt(1);
int type = resultSet.getInt(2);
String idCard = resultSet.getString(3);
String examCard = resultSet.getString(4);
String studentName = resultSet.getString(5);
String locatoin = resultSet.getString(6);
int grade = resultSet.getInt(7); Student student = new Student(FlowId, type, idCard, examCard,
studentName, locatoin, grade); students.add(student); } } catch (Exception e) {
e.printStackTrace();
} finally { // 关闭资源
try {
if (resultSet != null) {
resultSet.close();
}
} catch (SQLException e) {
e.printStackTrace();
} try {
if (preparedStatement != null) {
preparedStatement.close();
}
} catch (SQLException e) {
e.printStackTrace();
} try {
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
} return students;
} public boolean deleteByFlowId(int flowId){ Connection connection = null;
PreparedStatement preparedStatement = null;
boolean flage = false; try { String driverClass = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://127.0.0.1:3306/atguigu";
String user = "root";
String password = "zhangzhen";
// 加载驱动类
Class.forName(driverClass);
connection = DriverManager.getConnection(url, user, password); String sql = "DELETE FROM student WHERE FlowID = ?"; preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1, flowId);
int result = preparedStatement.executeUpdate();
if(result >= 0){
flage = true;
} } catch (Exception e) {
e.printStackTrace();
} finally { // 关闭资源 try {
if (preparedStatement != null) {
preparedStatement.close();
}
} catch (SQLException e) {
e.printStackTrace();
} try {
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
} return flage;
} }

  6)Student.java

 package com.jason.testMVC;

 /**
*
* @author: jason
* @time:2016年5月24日下午11:31:08
* @description:
*/
public class Student {
private int flowId; private int type; private String idCard; private String examCard; private String studentName; private String location; private int grade; public Integer getFlowId() {
return flowId;
} public void setFlowId(Integer flowId) {
this.flowId = flowId;
} public int getType() {
return type;
} public void setType(int type) {
this.type = type;
} public String getIdCard() {
return idCard;
} public void setIdCard(String idCard) {
this.idCard = idCard;
} public String getExamCard() {
return examCard;
} public void setExamCard(String examCard) {
this.examCard = examCard;
} public String getStudentName() {
return studentName;
} public void setStudentName(String studentName) {
this.studentName = studentName;
} public String getLocation() {
return location;
} public void setLocation(String location) {
this.location = location;
} public int getGrade() {
return grade;
} public void setGrade(int grade) {
this.grade = grade;
} public Student(Integer flowId, int type, String idCard, String examCard,
String studentName, String location, int grade) {
super();
this.flowId = flowId;
this.type = type;
this.idCard = idCard;
this.examCard = examCard;
this.studentName = studentName;
this.location = location;
this.grade = grade;
} //用于反射
public Student() { } @Override
public String toString() {
return "Student [flowId=" + flowId + ", type=" + type + ", idCard="
+ idCard + ", examCard=" + examCard + ", studentName="
+ studentName + ", location=" + location + ", grade=" + grade
+ "]";
} }

5.简单总结

 1)对于MVC设计模式的认识

  ① M: Model. Dao

  ② V: View. JSP, 在页面上填写 Java 代码实现显示

  ③ C: Controller. Serlvet:

      I. 受理请求

       II. 获取请求参数

III. 调用 DAO 方法

       IV. 可能会把 DAO 方法的返回值放入request 中

      V. 转发(或重定向)页面

  2)问题和足

  问题:什么时候转发,什么时候重定向 ? 若目标的响应页面不需要从 request 中读取任何值,则可以使用重定向。(还可以防止表单的重复提交)

  不足: I. 代码臃肿,结构不清楚。        解决方案:使用数据库连接池,DBUtils,JDBCUtils 工具类,DAO 基类;

        II. 一个请求一个 Serlvet 不好。    解决方案:一个模块使用一个 Serlvet,即多个请求可以使用一个 Servlet;

     III. 使用不友好。            解决方案:在页面上加入 jQuery 操作提示,如删除,保存等。