Application of MVC Design Pattern in JavaWeb (1)

Basic Concepts of MVC

  • Model (model) Model is the main part of the application, the model represents business data and business logic. A model can provide data for multiple views. Code reusability is improved because code applied to a model only needs to be written once and can be reused by multiple views.
  • View (view) A view is an interface that a user sees and interacts with, and works as follows
    - a view displays relevant data to the user.
    - Accept user input.
    - Does not do any actual business processing
  • Controller (controller) The controller accepts user input and invokes models and views to complete the user's needs. The controller receives the request and decides which model component
    to call to process the request, and then decides which view to call to display the data returned by the model processing.
  • Schematicwrite picture description here

case analysis

call situationwrite picture description here


Implementation code
StudentDao.java

package com.anqi.javaWeb.mvc;

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 void deleteStudentByFlowId(Integer flowId) {
            Connection connection = null;
            PreparedStatement preparedStatement = null;

            try {
                String driverClass = "com.mysql.jdbc.Driver";
                String url = "jdbc:mysql:///db_students";
                String user ="root";
                String password = "1995";

                Class.forName(driverClass);
                connection = DriverManager.getConnection(url, user, password);

                String sql = "DELETE FROM t_student WHERE flow_id = ?";
                preparedStatement = connection.prepareStatement(sql);

                preparedStatement.setInt(1, flowId);
                preparedStatement.execute();
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                if(preparedStatement != null) {
                    try {
                        preparedStatement.close();
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }   
                }
                if(connection != null) {
                    try {
                        connection.close();
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }   
                }

            }

        }

        public List<Student> getAll(){

            List<Student> students = new ArrayList<>();         
            Connection connection = null;
            PreparedStatement preparedStatement = null;
            ResultSet resultSet = null;

            try {
                String driverClass = "com.mysql.jdbc.Driver";
                String url = "jdbc:mysql:///db_students";
                String user ="root";
                String password = "1995";

                Class.forName(driverClass);
                connection = DriverManager.getConnection(url, user, password);

                String sql = "SELECT flow_id, type, id_card, exam_card, location, grade "
                        + "FROM t_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 location = resultSet.getString(5);
                    int grade = resultSet.getInt(6);

                    Student student = new Student(flowId, type, idCard, examCard, location, grade);
                    students.add(student);          
                    }
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                if(resultSet != null) {
                    try {
                        resultSet.close();
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }   
                }
                if(preparedStatement != null) {
                    try {
                        preparedStatement.close();
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }   
                }
                if(connection != null) {
                    try {
                        connection.close();
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }   
                }

            }

            return students;
        }
}

ListAllStudentsServlet.java

package com.anqi.javaWeb.mvc;

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;
@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);
    }

}

DeleteStudentServlet.java

package com.anqi.javaWeb.mvc;

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;

@WebServlet("/deleteStudent")
public class DeleteStudentServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String flowId = request.getParameter("flowId");

        StudentDao studentDao = new StudentDao();
        studentDao.deleteStudentByFlowId(Integer.parseInt(flowId));

        request.getRequestDispatcher("/sucess.jsp").forward(request, response);
    }

}

test.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>
    <a href = "listAllStudents">List All Students</a>
</body>
</html>

students.jsp

<%@page import="com.anqi.javaWeb.mvc.Student"%>
<%@page import="org.apache.jasper.tagplugins.jstl.core.ForEach"%>
<%@page import="java.util.List"%>
<%@ 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>

    <%
        List<Student> stus = (List<Student>)request.getAttribute("students");
    %>
    <table border = "1" cellpadding = "10" cellspacing = "0">

        <tr>
            <th>FlowId</th>
            <th>Type</th>
            <th>IdCard</th>
            <th>ExamCard</th>
            <th>Location</th>
            <th>Grade</th>
            <th>Delete</th>
        </tr>
        <%
            for(Student s : stus){
        %>
            <tr>
                <td><%= s.getFlowId() %></td>
                <td><%= s.getType() %></td>
                <td><%= s.getIdCard() %></td>
                <td><%= s.getExamCard() %></td>
                <td><%= s.getLocation() %></td>
                <td><%= s.getGrade() %></td>
                <td><a href = "deleteStudent?flowId=<%=s.getFlowId()%>">Delete</a></td>
            </tr>
        <%
            }
        %>
    </table>
</body>
</html>

sucess.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>

    删除操作成功!
    <br><br>
    <a href = "listAllStudents">List All Students</a>
</body>
</html>

operation result

write picture description here
write picture description here
write picture description here
write picture description here

final analysis

【关于MVC 】

1.M: Model.Dao
2.V: View.JSP,在页面上填写Java代码实现显示
3.C: Controller.Serivet:

【过程】
1.受理请求
2.获取请求参数
3.调用DAO方法
4.可能会把DAO 方法的返回值放入request 中
5.转发(或重定向)页面

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

【不足】
1.使用数据库连接池,DBUtils,JDBCUtils 工具类,DAO 基类
2.一个请求一个Sertvet 不好!一个模块使用一个Servet,即多个请求可
以使用一个Servlet
3.在页面上加入jQuery提示

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325683681&siteId=291194637