写Java Web项目时会发现,一个中型或者大型项目 随着代码的增多,会发现:代码既可以写在src目录下,也可以 写在WebContent目录下。src下可以建很多包 ,WebContent下可以建很多文件夹。 所以问题就来了:一个新的类 到底往哪个目录下的哪个文件夹里写? 此时解决办法就是:需要一个模式去规范,到底哪个类该往哪里写。

1.MVC设计模式

Web MVC中的M(模型) - V(视图) - C(控制器)概念和标准MVC概念一样,我们再看一下Web MVC标准架构,如下图所示:
image.png
在Web MVC模式下,模型无法主动推数据给视图,如果用户想要视图更新,需要再发送一次请求(即请求-响应模型)。
M:(Model) 模型 : 应用程序的核心功能,管理这个模块中用的数据和值(bean,dao);

  1. JavaBeans :是Java中一种特殊的类(换言之:JavaBean就是一个Java类).
  2. 一个Java ,满足以下要求,则可称为一个JavaBean
  3. a. public修饰的类,提供public 无参构造方法
  4. b. 所有属性 都是private
  5. C. 提供gettersetter方法
  6. 从使用层面来看,JavaBean分为2大类:
  7. a. 封装业务逻辑的JavaBean(eg:LoginDao.java 封装了登录逻辑)
  8. b. 封装数据的JavaBean(实体类:egStudent.java Vadio.java 。往往对应于数据库中的一张表,即数据库
  9. 中有个Student表,项目中就有个Student.java类)通常:表名=类名,列名=属性名
  10. JavaBean是一个可以重复使用的组件,通过编写一个组件来实现某种通用功能,“一次编写、任何地方执行、任何地方重
  11. 用”。

V(View )视图: 视图提供模型的展示,管理模型如何显示给用户,它是应用程序的外观;(jsp/html)

C(Controller)控制器: 对用户的输入做出反应,管理用户和视图的交互,是连接模型和视图的枢纽。(servlet/service)

MVC用于将web(UI)层进行职责解耦

说明:mvc设计模式(不属于23种设计模式)

2.三层架构

三层架构 通常意义上的三层架构就是将整个业务应用划分为:表现层(UI)、业务逻辑层(BLL)、数据访问层(DAL)。区分层次的目的即为了“高内聚,低耦合”的思想。

1、表现层(UI):通俗讲就是展现给用户的界面,即用户在使用一个系统的时候他的所见所得。 jsp/html

2、业务逻辑层(BLL):
针对具体问题的操作,也可以说是对数据层的操作,对数据业务逻辑处理。servlet,service

3、数据访问层(DAL):
该层所做事务直接操作数据库,针对数据的增添、删除、修改、更新、查找等。dao表现层实现的代表作品是Struts,springmvc框架,业务层实现的代表作品是Spring,持久层实现的代表作品是Hibernate,mybatis。

层就相当于一个黑盒子,我们不用知道它内部怎么实现,只需要知道如何去调用它就行了。每层只与上下相邻的两层打交道。当一层内部由于技术变迁发生变化时,只要接口不变,其他层不用做任何改变。分层之后灵活性提高,也便于团队分工开发。

3.三层架构和MVC的区别与联系

image.png
MVC是 Model-View-Controller,严格说这三个加起来以后才是三层架构中的UI层,也就是说,MVC把三层架构中的UI层再度进行了分化,分成了控制器、视图、实体三个部分,控制器完成页面逻辑,通过实体来与界面层完成通话;而C层直接与三层中的BLL进行对话。

MVC可以是三层中的一个表现层框架,属于表现层。三层和mvc可以共存。

三层是基于业务逻辑来分的,而MVC是基于页面来分的。

MVC主要用于表现层,3层主要用于体系架构,3层一般是表现层、中间层、数据层,其中表现层又可以分成M、V、C,(Model View Controller)模型-视图-控制器

MVC是表现模式(Presentation Pattern)

三层架构是典型的架构模式(Architecture Pattern)

三层架构的分层模式是典型的上下关系,上层依赖于下层。但MVC作为表现模式是不存在上下关系的,而是相互协作关系。即使将MVC当作架构模式,也不是分层模式。MVC和三层架构基本没有可比性,是应用于不同领域的技术。

4.小试牛刀

使用mvc实现一个数据的增删改查的交互。

1、代码

bean:student

  1. package com.zh.bean;
  2. /**
  3. * @Author: deemoHui
  4. * @Description:
  5. * @Date Created in 2020-09-08 19:39
  6. * @Modified By:
  7. */
  8. public class Student {
  9. private int studentId;
  10. private String studentNo;
  11. private String studentName;
  12. private int studentAge;
  13. private int gradeId;
  14. public Student() {
  15. }
  16. public Student(int studentId, String studentNo, String studentName, int studentAge, int gradeId) {
  17. this.studentId = studentId;
  18. this.studentNo = studentNo;
  19. this.studentName = studentName;
  20. this.studentAge = studentAge;
  21. this.gradeId = gradeId;
  22. }
  23. public int getStudentId() {
  24. return studentId;
  25. }
  26. public void setStudentId(int studentId) {
  27. this.studentId = studentId;
  28. }
  29. public String getStudentNo() {
  30. return studentNo;
  31. }
  32. public void setStudentNo(String studentNo) {
  33. this.studentNo = studentNo;
  34. }
  35. public String getStudentName() {
  36. return studentName;
  37. }
  38. public void setStudentName(String studentName) {
  39. this.studentName = studentName;
  40. }
  41. public int getStudentAge() {
  42. return studentAge;
  43. }
  44. public void setStudentAge(int studentAge) {
  45. this.studentAge = studentAge;
  46. }
  47. public int getGradeId() {
  48. return gradeId;
  49. }
  50. public void setGradeId(int gradeId) {
  51. this.gradeId = gradeId;
  52. }
  53. }

dao:

  1. package com.zh.dao;
  2. import com.zh.bean.Student;
  3. import java.util.List;
  4. /**
  5. @Author: deemoHui
  6. @Description:
  7. @Date Created in 2020-09-08 19:43
  8. @Modified By:
  9. */
  10. public interface StudentDao {
  11. /**
  12. * 增加
  13. * @param student 学生
  14. * @return 是否添加成功
  15. */
  16. public boolean add(Student student);
  17. /**
  18. * 删除
  19. * @param student 学生
  20. * @return 是否删除成功
  21. */
  22. public boolean delete(Student student);
  23. /**
  24. * 修改
  25. * @param student 学生
  26. * @return 是否更改成功
  27. */
  28. public boolean update(Student student);
  29. /**
  30. * 查询
  31. * @return 学生列表
  32. */
  33. public List<Student> getAll();
  34. }
  1. package com.zh.dao.implement;
  2. import com.zh.bean.Student;
  3. import com.zh.dao.StudentDao;
  4. import com.zh.util.DruidUtil;
  5. import java.sql.Connection;
  6. import java.sql.PreparedStatement;
  7. import java.sql.ResultSet;
  8. import java.sql.SQLException;
  9. import java.util.ArrayList;
  10. import java.util.List;
  11. /**
  12. * @Author: deemoHui
  13. * @Description:
  14. * @Date Created in 2020-09-08 19:41
  15. * @Modified By:
  16. */
  17. public class StudentDaoImpl extends DruidUtil implements StudentDao {
  18. @Override
  19. public boolean add(Student student) {
  20. String studentNo = student.getStudentNo();
  21. String studentName = student.getStudentName();
  22. int studentAge = student.getStudentAge();
  23. int gradeId;
  24. gradeId = student.getGradeId();
  25. Connection connection = null;
  26. PreparedStatement preparedStatement = null;
  27. try {
  28. connection = getConnection();
  29. if (connection != null) {
  30. preparedStatement = connection.prepareStatement("INSERT INTO student VALUES (null, ?, ?, ?, ?)");
  31. preparedStatement.setString(1, studentNo);
  32. preparedStatement.setString(2, studentName);
  33. preparedStatement.setInt(3, studentAge);
  34. preparedStatement.setInt(4, gradeId);
  35. preparedStatement.execute();
  36. return true;
  37. }
  38. } catch (SQLException e) {
  39. e.printStackTrace();
  40. } finally {
  41. close(connection, preparedStatement);
  42. }
  43. return false;
  44. }
  45. @Override
  46. public boolean delete(Student student) {
  47. String studentNo = student.getStudentNo();
  48. Connection connection = null;
  49. PreparedStatement preparedStatement = null;
  50. try {
  51. connection = getConnection();
  52. if (connection != null) {
  53. preparedStatement = connection.prepareStatement("delete from student where studentno = ?");
  54. preparedStatement.setString(1, studentNo);
  55. preparedStatement.execute();
  56. return true;
  57. }
  58. } catch (SQLException e) {
  59. e.printStackTrace();
  60. } finally {
  61. close(connection, preparedStatement);
  62. }
  63. return false;
  64. }
  65. @Override
  66. public boolean update(Student student) {
  67. String studentNo = student.getStudentNo();
  68. String studentName = student.getStudentName();
  69. int studentAge = student.getStudentAge();
  70. int gradeId;
  71. gradeId = student.getGradeId();
  72. Connection connection = null;
  73. PreparedStatement preparedStatement = null;
  74. try {
  75. connection = getConnection();
  76. if (connection != null) {
  77. preparedStatement = connection.prepareStatement("update student set stuname = ?,stuage = ?,gradeid = ? where studentno = ?");
  78. preparedStatement.setString(1, studentName);
  79. preparedStatement.setInt(2, studentAge);
  80. preparedStatement.setInt(3, gradeId);
  81. preparedStatement.setString(4, studentNo);
  82. preparedStatement.execute();
  83. return true;
  84. }
  85. } catch (SQLException e) {
  86. e.printStackTrace();
  87. } finally {
  88. close(connection, preparedStatement);
  89. }
  90. return false;
  91. }
  92. @Override
  93. public List<Student> getAll() {
  94. List<Student> list = new ArrayList<>();
  95. Connection connection = null;
  96. PreparedStatement preparedStatement = null;
  97. ResultSet resultSet = null;
  98. try {
  99. connection = getConnection();
  100. String sql = "select * from student";
  101. if (connection != null) {
  102. preparedStatement = connection.prepareStatement(sql);
  103. resultSet = preparedStatement.executeQuery();
  104. while (resultSet.next()) {
  105. Student student = new Student();
  106. student.setStudentId(resultSet.getInt("studentid"));
  107. student.setStudentNo(resultSet.getString("studentno"));
  108. student.setStudentName(resultSet.getString("stuname"));
  109. student.setStudentAge(resultSet.getInt("stuage"));
  110. student.setGradeId(resultSet.getInt("gradeid"));
  111. list.add(student);
  112. }
  113. }
  114. } catch (SQLException e) {
  115. e.printStackTrace();
  116. } finally {
  117. close(connection, preparedStatement, resultSet);
  118. }
  119. return list;
  120. }
  121. }

service:

package com.zh.service;

import com.zh.bean.Student;

import java.util.List;

/**
 * @Author: deemoHui
 * @Description:
 * @Date Created in 2020-09-08 19:45
 * @Modified By:
 */
public interface StudentService {
    /**
     * 增加
     * @param student 学生
     * @return 是否添加成功
     */
    public boolean add(Student student);

    /**
     * 删除
     * @param student 学生
     * @return 是否删除成功
     */
    public boolean delete(Student student);

    /**
     * 修改
     * @param student 学生
     * @return 是否更改成功
     */
    public boolean update(Student student);

    /**
     * 查询
     * @return 学生列表
     */
    public List<Student> getAll();
}
package com.zh.service.implement;

import com.zh.bean.Student;
import com.zh.dao.StudentDao;
import com.zh.dao.implement.StudentDaoImpl;
import com.zh.service.StudentService;

import java.util.List;

/**
 * @Author: deemoHui
 * @Description:
 * @Date Created in 2020-09-08 19:45
 * @Modified By:
 */
public class StudentServiceImpl implements StudentService {
    private final StudentDao dao = new StudentDaoImpl();

    @Override
    public boolean add(Student student) {
        return dao.add(student);
    }

    @Override
    public boolean delete(Student student) {
        return dao.delete(student);
    }

    @Override
    public boolean update(Student student) {
        return dao.update(student);
    }

    @Override
    public List<Student> getAll() {
        return dao.getAll();
    }

}

util:

package com.zh.util;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import javax.xml.transform.Result;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class DruidUtil {

    private static DataSource ds;
    static{
        try {
            Properties ppt = new Properties();
            ppt.load(DruidUtil.class.getClassLoader().getResourceAsStream("druid.properties"));
            ds = DruidDataSourceFactory.createDataSource(ppt);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 从连接池中取出一个连接给用户
     * @return
     */
    public static Connection getConnection(){
        try {
            return ds.getConnection();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return null;
    }


    public static void close(Connection conn, Statement state, ResultSet rs){
        try {
            rs.close();
        } catch (Exception throwables) {
            throwables.printStackTrace();
        }
        try {
            state.close();
        } catch (Exception throwables) {
            throwables.printStackTrace();
        }
        try {
            conn.close();
        } catch (Exception throwables) {
            throwables.printStackTrace();
        }
    }

    public static void close(Connection conn, Statement state){
        try {
            state.close();
        } catch (Exception throwables) {
            throwables.printStackTrace();
        }
        try {
            conn.close();
        } catch (Exception throwables) {
            throwables.printStackTrace();
        }
    }
}

web:
AddStudentServlet

package com.zh.web;

import com.zh.bean.Student;
import com.zh.service.StudentService;
import com.zh.service.implement.StudentServiceImpl;

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 javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * @Author: deemoHui
 * @Description:
 * @Date Created in 2020-09-08 20:43
 * @Modified By:
 */
@WebServlet(value = "/addStudent")
public class AddStudentServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter writer = resp.getWriter();
        //1.接受参数
        String studentNo = req.getParameter("studentNo");
        String studentName = req.getParameter("studentName");
        int studentAge = Integer.parseInt(req.getParameter("studentAge"));
        int gradeId = Integer.parseInt(req.getParameter("gradeId"));
        //2.调取service方法
        Student student = new Student(-1, studentNo, studentName, studentAge, gradeId);
        StudentService studentService=new StudentServiceImpl();
        boolean status = studentService.add(student);
        //3.跳转页面
        // 插入成功,弹窗提示,并查询后跳转到展示界面
        if(status){
            // 查询所有,跳转展示页面
            List<Student> students = studentService.getAll();
            HttpSession session = req.getSession();
            session.setAttribute("students",students);
            writer.write("<script>alert('添加成功');location.href='/show.jsp'</script>");
            // req.getRequestDispatcher("show.jsp").forward(req,resp);
        }else{
            writer.write("<script>alert('添加失败');location.href='/show.jsp'</script>");
        }


    }
}

DeleteStudentServlet

package com.zh.web;

import com.zh.bean.Student;
import com.zh.service.StudentService;
import com.zh.service.implement.StudentServiceImpl;

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 javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * @Author: deemoHui
 * @Description:
 * @Date Created in 2020-09-08 20:43
 * @Modified By:
 */
@WebServlet(value = "/deleteStudent")
public class DeleteStudentServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter writer = resp.getWriter();
        //1.接受参数
        String studentNo = req.getParameter("studentNo");
        String studentName = req.getParameter("studentName");
        String studentAge1 = req.getParameter("studentAge");
        System.out.println(studentNo);
        System.out.println(studentName);
        System.out.println(studentAge1);
        System.out.println("----------------------------------------");
        int studentAge = Integer.parseInt(studentAge1);
        int gradeId = Integer.parseInt(req.getParameter("gradeId"));
        //2.调取service方法
        Student student = new Student(-1, studentNo, studentName, studentAge, gradeId);
        StudentService studentService=new StudentServiceImpl();
        boolean status = studentService.delete(student);
        //3.跳转页面
        // 插入成功,弹窗提示,并查询后跳转到展示界面
        if(status){
            List<Student> students = studentService.getAll();
            HttpSession session = req.getSession();
            session.setAttribute("students",students);
            writer.write("<script>alert('删除成功');location.href='/show.jsp'</script>");
            // req.getRequestDispatcher("show.jsp").forward(req,resp);
        }else{
            writer.write("<script>alert('删除失败');location.href='/show.jsp'</script>");
        }
    }
}

GetAllStudentServlet

package com.zh.web;

import com.zh.bean.Student;
import com.zh.service.StudentService;
import com.zh.service.implement.StudentServiceImpl;

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 javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

/**
 * @Author: deemoHui
 * @Description:
 * @Date Created in 2020-09-08 20:42
 * @Modified By:
 */
@WebServlet(value = "/getAllStudent")
public class GetAllStudentServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.接受参数
        //2.调取service方法
        StudentService studentService=new StudentServiceImpl();
        List<Student> students = studentService.getAll();
        //3.跳转页面
        HttpSession session = req.getSession();
        session.setAttribute("students",students);
        req.getRequestDispatcher("show.jsp").forward(req,resp);
    }
}

UpdateStudentServlet

package com.zh.web;

import com.zh.bean.Student;
import com.zh.service.StudentService;
import com.zh.service.implement.StudentServiceImpl;

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 javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * @Author: deemoHui
 * @Description:
 * @Date Created in 2020-09-08 20:43
 * @Modified By:
 */
@WebServlet(value = "/updateStudent")
public class UpdateStudentServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter writer = resp.getWriter();
        //1.接受参数
        String studentNo = req.getParameter("studentNo");
        String studentName = req.getParameter("studentName");
        int studentAge = Integer.parseInt(req.getParameter("studentAge"));
        int gradeId = Integer.parseInt(req.getParameter("gradeId"));
        //2.调取service方法
        Student student = new Student(-1, studentNo, studentName, studentAge, gradeId);
        StudentService studentService=new StudentServiceImpl();
        boolean status = studentService.update(student);
        //3.跳转页面
        // 插入成功,弹窗提示,并查询后跳转到展示界面
        if(status){
            // 查询所有,跳转展示页面
            List<Student> students = studentService.getAll();
            HttpSession session = req.getSession();
            session.setAttribute("students",students);
            writer.write("<script>alert('修改成功');location.href='/show.jsp'</script>");
            // req.getRequestDispatcher("show.jsp").forward(req,resp);
        }else{
            writer.write("<script>alert('修改失败');location.href='/show.jsp'</script>");
        }
    }
}

druid.properties

url=jdbc:mysql://localhost:3306/mvc?useUnicode=true&characterEncoding=utf-8
username=root
#password=123456
driverClassName=com.mysql.jdbc.Driver
initialSize=5
maxActive=10
minIdle=5
maxWait=3000

index.jsp

<%--
  Created by IntelliJ IDEA.
  User: zlz1314
  Date: 2020/9/8
  Time: 19:33
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>班班班</title>
  </head>
  <body>
  <h1>欢迎来到本班级!<a href="getAllStudent">查看所有学生</a></h1>
  </body>
</html>

show.jsp

<%--
  Created by IntelliJ IDEA.
  User: zlz1314
  Date: 2020/9/8
  Time: 21:29
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>道徒</title>
    <style>
        div,button{margin:0px;padding:0px;}
        .data{float: left;}
        .btn{float: left;width: 100px;height: 200px; margin-left: 50px;}
        #add{display: none;float: left;margin-top: -25px;}
        #update{display: none;float: left;margin-top: -25px;}
        #del{display: none;float: left;margin-top: -25px;}
    </style>
    <script src="./jquery-3.5.0.min.js"></script>
</head>
<body>
<h1>所有学生信息:</h1>
<div class="data">
    <table id="tid" width="500" border="1" cellpadding="10">
        <thead>
        <tr>
            <th>学号</th>
            <th>姓名</th>
            <th>年龄</th>
            <th>班级</th>
            <th colspan="2">操作</th>
        </tr>
        </thead>
        <tbody>
        <c:forEach items="${students}" var="student">
            <tr>
                <td>${student.studentNo}</td>
                <td>${student.studentName}</td>
                <td>${student.studentAge}</td>
                <td>${student.gradeId}</td>
                <td><button >删除</button></td>
                <td><button >修改</button></td>
            </tr>
        </c:forEach>
        </tbody>
    </table>
</div>

<div class="btn">
    <button class="addb">添加</button>
</div>

<div id="add">
    <h2>添加学生信息</h2>
    <form action="addStudent" name="add" method="POST" >
        学号:<input type="text" name="studentNo"/><br/><br/>
        姓名:<input type="text" name="studentName"/><br/><br/>
        年龄:<input type="text" name="studentAge"/><br/><br/>
        班级:<input type="text" name="gradeId"/><br/><br/>
        <input type="submit" value="添加"/>
    </form>
</div>

<div id="update">
    <h2>修改学生信息</h2>
    <form action="updateStudent" name="update" method="POST" >
        学号:<input type="text" name="studentNo" readonly="readonly"><br/><br/>
        姓名:<input type="text" name="studentName"/><br/><br/>
        年龄:<input type="text" name="studentAge"/><br/><br/>
        班级:<input type="text" name="gradeId"/><br/><br/>
        <input type="submit" value="修改"/>
    </form>
</div>

<div id="del">
    <h2>要删除的学生信息</h2>
    <form action="deleteStudent" name="del" method="POST" >
        学号:<input type="text" name="studentNo" readonly="readonly"><br/><br/>
        姓名:<input type="text" name="studentName" readonly="readonly"><br/><br/>
        年龄:<input type="text" name="studentAge" readonly="readonly"><br/><br/>
        班级:<input type="text" name="gradeId" readonly="readonly"><br/><br/>
        <input type="submit" value="确认删除"/>
    </form>
</div>

</body>
<script>
    //删除
    $("#tid tbody tr td:nth-child(5)").click(function(){
        $("#add").css({"display":"none"});
        $("#update").css({"display":"none"});
        $("#del").css({"display":"block"});
        var tr = $(this).prevAll();
        // console.log($(tr[3]).html());
        $("#del input[name = 'studentNo']").attr("value",$(tr[3]).html());
        $("#del input[name = 'studentName']").attr("value",$(tr[2]).html());
        $("#del input[name = 'studentAge']").attr("value",$(tr[1]).html());
        $("#del input[name = 'gradeId']").attr("value",$(tr[0]).html());
    })

    // 添加
    $(".addb").click(function(){
        $("#del").css({"display":"none"});
        $("#update").css({"display":"none"});
        $("#add").css({"display":"block"})
    })
    // 修改
    $("#tid tbody tr td:last-child").click(function(){
        $("#add").css({"display":"none"});
        $("#del").css({"display":"none"});
        $("#update").css({"display":"block"});
        var tr = $(this).prevAll();
        $("#update input[name = 'studentNo']").attr("value",$(tr[4]).html());
        $("#update input[name = 'studentName']").attr("value",$(tr[3]).html());
        $("#update input[name = 'studentAge']").attr("value",$(tr[2]).html());
        $("#update input[name = 'gradeId']").attr("value",$(tr[1]).html());
    });
</script>
</html>

lib
image.png

2、运行截图

image.png
image.png
image.png
image.png
image.png
image.png
image.png
image.png
image.png
image.png
image.png

3、总结

1、总体逻辑

  • 先建立各个层次的包
  • 写Bean类
  • 写Dao类
  • 写service类
  • 写servlet类
  • 写JSP

    2、如何通过js点击事件获取到所有的td中的值,并把其填写到右侧的对应input中?

    我最初的设想是,通过被点击的 this 获取其 parent,再按照eq函数获取,但是发现,td获取到的parent不对,不是tr,不能通过tr的eq来获取其他的td。查阅了挺久手册之后,通过prevall获取到了其前边的所有td,但是顺序是反的
    var tr = $(this).prevAll();
    $("#del input[name = 'studentNo']").attr("value",$(tr[3]).html());
    $("#del input[name = 'studentName']").attr("value",$(tr[2]).html());
    $("#del input[name = 'studentAge']").attr("value",$(tr[1]).html());
    $("#del input[name = 'gradeId']").attr("value",$(tr[0]).html());
    
    即tr[0]是被点击元素的上一个,而不是tr中的第一个td。
    然后是填充input内容,这里需要使用attr(“value”,$(tr[0]).html()),而不是html或者text,因为是属性值。

3、对于修改和删除,不希望更改某些数据,怎么做(disabled 和 readonly)

对于修改,为了保证能从数据库查询到数据,不能让他全部修改,我决定保留学号,不被修改。对于删除,则是所有信息都不被操作,怎么实现呢?
我开始使用了disabled,但是这会导致一个问题,即提交表单的时候,是没有数据提交过去的,即servlet中使用getParameter是获取到的null,解决办法是使用readonly,但是效果我不是很满意,因为readonly看上去还是可以点击的,只是点击了之后没有光标。