• [原创]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

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

       

      2)des.jsp

     1 <%@ page language="java" contentType="text/html; charset=UTF-8"
     2     pageEncoding="UTF-8"%>
     3 <%@ page import="java.util.List"%>
     4 <%@ page import="com.jason.testMVC.Student"%>
     5 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
     6 <html>
     7 <head>
     8 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
     9 <title>des</title>
    10 </head>
    11 <body>
    12     <%
    13         List<Student> stus = (List<Student>) request
    14                 .getAttribute("students");
    15 
    16         if (stus == null) {
    17             System.out.println("stus is null");
    18         } else {
    19     %>
    20     <table border="1" cellpadding="10" cellspacing="0">
    21         <tr>
    22             <th>FlowId</th>
    23             <th>Type</th>
    24             <th>IdCard</th>
    25             <th>ExamCard</th>
    26             <th>StudentName</th>
    27             <th>Location</th>
    28             <th>Grade</th>
    29             <th>Delete</th>
    30         </tr>
    31         <%
    32             for (Student stu : stus) {
    33         %>
    34         <tr>
    35             <td><%=stu.getExamCard()%></td>
    36             <td><%=stu.getType()%></td>
    37             <td><%=stu.getIdCard()%></td>
    38             <td><%=stu.getExamCard()%></td>
    39             <td><%=stu.getStudentName()%></td>
    40             <td><%=stu.getLocation()%></td>
    41             <td><%=stu.getGrade()%></td>
    42             <td><a href="deletStudent?flowId=<%=stu.getFlowId() %>"/>Delete</td>   //通过这个种方式,向servlet传入flowId参数
    43         </tr>
    44         <%    
    45                 }
    46             }
    47         %>
    48     </table>
    49 
    50 </body>
    51 </html>

      3)success.jsp

     1 <%@ page language="java" contentType="text/html; charset=UTF-8"
     2     pageEncoding="UTF-8"%>
     3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
     4 <html>
     5 <head>
     6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
     7 <title>Insert title here</title>
     8 </head>
     9 <body>
    10     
    11     
    12     <h1>删除成功</h1>
    13     <a href="listAllStudents">List All Students</a>
    14     
    15     
    16 </body>
    17 </html>

      4)ListAllStudentsServlet.java

     1 package com.jason.testMVC;
     2 
     3 import java.io.IOException;
     4 import java.util.List;
     5 
     6 import javax.servlet.ServletException;
     7 import javax.servlet.annotation.WebServlet;
     8 import javax.servlet.http.HttpServlet;
     9 import javax.servlet.http.HttpServletRequest;
    10 import javax.servlet.http.HttpServletResponse;
    11 
    12 /**
    13  * Servlet implementation class ListAllStudentsServlet
    14  */
    15 @WebServlet("/listAllStudents")
    16 public class ListAllStudentsServlet extends HttpServlet {
    17     private static final long serialVersionUID = 1L;
    18 
    19     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    20     
    21             StudentDao studentDao = new StudentDao();
    22             List<Student>  students = studentDao.getAll();
    23             
    24             request.setAttribute("students", students);
    25         
    26             request.getRequestDispatcher("/students.jsp").forward(request, response);
    27     }
    28 
    29 }

       

      5)DeletStudentServlet.java 

     1 package com.jason.testMVC;
     2 
     3 import java.io.IOException;
     4 
     5 import javax.servlet.ServletException;
     6 import javax.servlet.annotation.WebServlet;
     7 import javax.servlet.http.HttpServlet;
     8 import javax.servlet.http.HttpServletRequest;
     9 import javax.servlet.http.HttpServletResponse;
    10 
    11 import com.sun.org.apache.xalan.internal.xsltc.compiler.sym;
    12 
    13 /**
    14  * Servlet implementation class DeletStudentServlet
    15  */
    16 
    17 
    18 @WebServlet("/deletStudent")
    19 public class DeletStudentServlet extends HttpServlet {
    20     private static final long serialVersionUID = 1L;
    21        
    22     
    23     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    24         
    25         String flowIdStr =   request.getParameter("flowId");
    26 //    int flowId = Integer.parseInt(flowIdStr);
    27 //        System.out.println(flowIdStr);
    28         
    29         StudentDao  studentDao = new StudentDao();
    30         boolean flage = studentDao.deleteByFlowId(Integer.parseInt(flowIdStr));
    31         
    32         if(flage){
    33             request.getRequestDispatcher("/success.jsp").forward(request, response);
    34         }else{
    35             System.out.println("删除失败");
    36         }
    37         
    38         
    39     }
    40 
    41     
    42 
    43 }

      6)StudentDao.java

      1 package com.jason.testMVC;
      2 
      3 import java.sql.Connection;
      4 import java.sql.DriverManager;
      5 import java.sql.PreparedStatement;
      6 import java.sql.ResultSet;
      7 import java.sql.SQLException;
      8 import java.util.ArrayList;
      9 import java.util.List;
     10 
     11 public class StudentDao {
     12         
     13     
     14     public List<Student> getAll() {
     15 
     16         List<Student> students = new ArrayList<Student>();
     17         Connection connection = null;
     18         PreparedStatement preparedStatement = null;
     19         ResultSet resultSet = null;
     20 
     21         try {
     22 
     23             String driverClass = "com.mysql.jdbc.Driver";
     24             String url = "jdbc:mysql://127.0.0.1:3306/atguigu";
     25             String user = "root";
     26             String password = "zhangzhen";
     27             // 加载驱动类
     28             Class.forName(driverClass);
     29             connection = DriverManager.getConnection(url, user, password);
     30             
     31             String sql = "SELECT *  FROM student";
     32             
     33             preparedStatement = connection.prepareStatement(sql);
     34             resultSet = preparedStatement.executeQuery();
     35 
     36             while (resultSet.next()) {
     37                 int FlowId = resultSet.getInt(1);
     38                 int type = resultSet.getInt(2);
     39                 String idCard = resultSet.getString(3);
     40                 String examCard = resultSet.getString(4);
     41                 String studentName = resultSet.getString(5);
     42                 String locatoin = resultSet.getString(6);
     43                 int grade = resultSet.getInt(7);
     44 
     45                 Student student = new Student(FlowId, type, idCard, examCard,
     46                         studentName, locatoin, grade);
     47                 
     48                 students.add(student);
     49 
     50             }
     51 
     52 
     53         } catch (Exception e) {
     54             e.printStackTrace();
     55         } finally {
     56 
     57             // 关闭资源
     58             try {
     59                 if (resultSet != null) {
     60                     resultSet.close();
     61                 }
     62             } catch (SQLException e) {
     63                 e.printStackTrace();
     64             }
     65 
     66             try {
     67                 if (preparedStatement != null) {
     68                     preparedStatement.close();
     69                 }
     70             } catch (SQLException e) {
     71                 e.printStackTrace();
     72             }
     73 
     74             try {
     75                 if (connection != null) {
     76                     connection.close();
     77                 }
     78             } catch (SQLException e) {
     79                 e.printStackTrace();
     80             }
     81         }
     82 
     83         return students;
     84     }
     85 
     86     public boolean deleteByFlowId(int flowId){
     87         
     88         Connection connection = null;
     89         PreparedStatement preparedStatement = null;
     90         boolean  flage = false;
     91         
     92         try {
     93 
     94             String driverClass = "com.mysql.jdbc.Driver";
     95             String url = "jdbc:mysql://127.0.0.1:3306/atguigu";
     96             String user = "root";
     97             String password = "zhangzhen";
     98             // 加载驱动类
     99             Class.forName(driverClass);
    100             connection = DriverManager.getConnection(url, user, password);
    101             
    102             String sql = "DELETE  FROM student WHERE FlowID = ?";
    103             
    104             preparedStatement = connection.prepareStatement(sql);
    105             preparedStatement.setInt(1, flowId);
    106             int result = preparedStatement.executeUpdate();
    107             if(result >= 0){
    108                 flage = true;
    109             }
    110 
    111         } catch (Exception e) {
    112             e.printStackTrace();
    113         } finally {
    114 
    115             // 关闭资源
    116             
    117 
    118             try {
    119                 if (preparedStatement != null) {
    120                     preparedStatement.close();
    121                 }
    122             } catch (SQLException e) {
    123                 e.printStackTrace();
    124             }
    125 
    126             try {
    127                 if (connection != null) {
    128                     connection.close();
    129                 }
    130             } catch (SQLException e) {
    131                 e.printStackTrace();
    132             }
    133         }
    134         
    135         return flage;
    136     }
    137     
    138     
    139 }

      6)Student.java

      1 package com.jason.testMVC;
      2 
      3 /**
      4  * 
      5  * @author: jason
      6  * @time:2016年5月24日下午11:31:08
      7  * @description:
      8  */
      9 public class Student {
     10     private int flowId;
     11     
     12     private int type;
     13     
     14     private String idCard;
     15     
     16     private String examCard;
     17     
     18     private String studentName;
     19     
     20     private String location;
     21     
     22     private int grade;
     23 
     24     public Integer getFlowId() {
     25         return flowId;
     26     }
     27 
     28     public void setFlowId(Integer flowId) {
     29         this.flowId = flowId;
     30     }
     31 
     32     public int getType() {
     33         return type;
     34     }
     35 
     36     public void setType(int type) {
     37         this.type = type;
     38     }
     39 
     40     public String getIdCard() {
     41         return idCard;
     42     }
     43 
     44     public void setIdCard(String idCard) {
     45         this.idCard = idCard;
     46     }
     47 
     48     public String getExamCard() {
     49         return examCard;
     50     }
     51 
     52     public void setExamCard(String examCard) {
     53         this.examCard = examCard;
     54     }
     55 
     56     public String getStudentName() {
     57         return studentName;
     58     }
     59 
     60     public void setStudentName(String studentName) {
     61         this.studentName = studentName;
     62     }
     63 
     64     public String getLocation() {
     65         return location;
     66     }
     67 
     68     public void setLocation(String location) {
     69         this.location = location;
     70     }
     71 
     72     public int getGrade() {
     73         return grade;
     74     }
     75 
     76     public void setGrade(int grade) {
     77         this.grade = grade;
     78     }
     79 
     80     public Student(Integer flowId, int type, String idCard, String examCard,
     81             String studentName, String location, int grade) {
     82         super();
     83         this.flowId = flowId;
     84         this.type = type;
     85         this.idCard = idCard;
     86         this.examCard = examCard;
     87         this.studentName = studentName;
     88         this.location = location;
     89         this.grade = grade;
     90     }
     91 
     92     //用于反射
     93     public Student() {
     94         
     95     }
     96 
     97     @Override
     98     public String toString() {
     99         return "Student [flowId=" + flowId + ", type=" + type + ", idCard="
    100                 + idCard + ", examCard=" + examCard + ", studentName="
    101                 + studentName + ", location=" + location + ", grade=" + grade
    102                 + "]";
    103     }
    104     
    105     
    106 
    107 }

    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 操作提示,如删除,保存等。

  • 相关阅读:
    C语言:求n(n<10000)以内的所有四叶玫瑰数。-将字符串s1和s2合并形成新的字符串s3,先取出1的第一个字符放入3,再取出2的第一个字符放入3,
    C语言:找出一个大于给定整数m且紧随m的素数,-求出能整除x且不是偶数的数的个数,
    C语言:将3*4矩阵中找出行最大,列最小的那个元素。-将低于平均值的人数作为函数返回值,将低于平均分的分数放入below数组中。
    C语言:将3*5矩阵中第k列的元素左移到第0列,第k列以后的每列元素依次左移,原来左边的各列依次绕到右边。-在m行m列的二维数组中存放如下规律的数据,
    C语言:将ss所指字符串中所有下标为奇数位置的字母转换为大写-将该字符串中的所有字符按ASCII码值升序排序后输出。-将a所指的4*3矩阵第k行的元素与第0行元素交换。
    C语言:将s所指字符串中下标为偶数同时ASCII值为奇数的字符删去,-将a所指字符串中的字符和b所指字符串中的字符的顺序交叉,-将形参s所指字符串中的所有数字字符顺序前移,
    C语言:将带头节点的单向链表结点域中的数据从小到大排序。-求出单向链表结点(不包括头节点)数据域中的最大值。-将M*N的二维数组中的数据,按行依次放入一维数组,
    C语言:判断字符串是否为回文,-函数fun将单向链表结点数据域为偶数的值累加起来。-用函数指针指向要调用的函数,并进行调用。
    C语言:去除一个字符串中所有的空格。-函数fun传入形参m,求t=1/2-1/3+1/4.....+1/m的值。-判断形参a指定的矩阵是不是“幻方“。
    C语言-对字符串二维数组各个元素进行比较-十进制数转化为其他进制数-进行规则矩阵的输出-190225
  • 原文地址:https://www.cnblogs.com/jasonHome/p/5526308.html
Copyright © 2020-2023  润新知