An MVC Example with Servlets and JSP – 使用Servlets和JSP的MVC实例

最后修改: 2018年 3月 2日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In this quick article, we’ll create a small web application that implements the Model View Controller (MVC) design pattern, using basic Servlets and JSPs.

在这篇快速的文章中,我们将使用基本的Servlets和JSP创建一个小型的Web应用,实现模型-视图-控制器(MVC)设计模式。

We’ll explore a little bit about how MVC works, and its key features before we move on to the implementation.

我们将探讨一下MVC是如何工作的,以及它的主要特点,然后再进入实施阶段。

2. Introduction to MVC

2.MVC简介

Model-View-Controller (MVC) is a pattern used in software engineering to separate the application logic from the user interface. As the name implies, the MVC pattern has three layers.

模型-视图-控制器(MVC)是软件工程中使用的一种模式,将应用逻辑与用户界面分开。顾名思义,MVC模式有三个层次。

The Model defines the business layer of the application, the Controller manages the flow of the application, and the View defines the presentation layer of the application.

模型定义了应用程序的业务层,控制器管理了应用程序的流程,而视图定义了应用程序的表现层。

Although the MVC pattern isn’t specific to web applications, it fits very well in this type of applications. In a Java context, the Model consists of simple Java classes, the Controller consists of servlets and the View consists of JSP pages.

尽管MVC模式并不是专门针对网络应用的,但它非常适用于这种类型的应用。在Java环境中,模型由简单的Java类组成,控制器由servlets组成,视图由JSP页面组成。

Here’re some key features of the pattern:

以下是该模式的一些主要特点。

  • It separates the presentation layer from the business layer
  • The Controller performs the action of invoking the Model and sending data to View
  • The Model is not even aware that it is used by some web application or a desktop application

Let’s have a look at each layer.

让我们来看看每一层。

2.1. The Model Layer

2.1.模型层

This is the data layer which contains business logic of the system, and also represents the state of the application.

这是数据层,包含了系统的业务逻辑,同时也代表了应用程序的状态。

It’s independent of the presentation layer, the controller fetches the data from the Model layer and sends it to the View layer.

它独立于表现层,控制器从模型层获取数据并将其发送到视图层。

2.2. The Controller Layer

2.2.控制器层

Controller layer acts as an interface between View and Model. It receives requests from the View layer and processes them, including the necessary validations.

控制器层作为视图和模型之间的一个接口。它接收来自视图层的请求并处理它们,包括必要的验证。

The requests are further sent to Model layer for data processing, and once they are processed, the data is sent back to the Controller and then displayed on the View.

这些请求被进一步发送到模型层进行数据处理,一旦处理完毕,数据被送回控制器,然后显示在视图上。

2.3. The View Layer

2.3.视图层

This layer represents the output of the application, usually some form of UI. The presentation layer is used to display the Model data fetched by the Controller.

这一层表示应用程序的输出,通常是某种形式的用户界面。表现层用于显示控制器获取的模型数据。

3. MVC With Servlets and JSP

3.使用Servlet和JSP的MVC

To implement a web application based on MVC design pattern, we’ll create the Student and StudentService classes – which will act as our Model layer.

为了实现一个基于MVC设计模式的Web应用程序,我们将创建StudentStudentService类,它们将作为我们的模型层。

StudentServlet class will act as a Controller, and for the presentation layer, we’ll create student-record.jsp page.

StudentServlet类将充当控制器,而对于表现层,我们将创建student-record.jsp页。

Now, let’s write these layers one by one and start with Student class:

现在,让我们一个一个地写这些层,从Student类开始。

public class Student {
    private int id;
    private String firstName;
    private String lastName;
	
    // constructors, getters and setters goes here
}

Let’s now write our StudentService which will process our business logic:

现在让我们编写我们的StudentService,它将处理我们的业务逻辑。

public class StudentService {

    public Optional<Student> getStudent(int id) {
        switch (id) {
            case 1:
                return Optional.of(new Student(1, "John", "Doe"));
            case 2:
                return Optional.of(new Student(2, "Jane", "Goodall"));
            case 3:
                return Optional.of(new Student(3, "Max", "Born"));
            default:
                return Optional.empty();
        }
    }
}

Now let’s create our Controller class StudentServlet:

现在让我们创建我们的控制器类StudentServlet

@WebServlet(
  name = "StudentServlet", 
  urlPatterns = "/student-record")
public class StudentServlet extends HttpServlet {

    private StudentService studentService = new StudentService();

    private void processRequest(
      HttpServletRequest request, HttpServletResponse response) 
      throws ServletException, IOException {

        String studentID = request.getParameter("id");
        if (studentID != null) {
            int id = Integer.parseInt(studentID);
            studentService.getStudent(id)
              .ifPresent(s -> request.setAttribute("studentRecord", s));
        }

        RequestDispatcher dispatcher = request.getRequestDispatcher(
          "/WEB-INF/jsp/student-record.jsp");
        dispatcher.forward(request, response);
    }

    @Override
    protected void doGet(
      HttpServletRequest request, HttpServletResponse response) 
      throws ServletException, IOException {

        processRequest(request, response);
    }

    @Override
    protected void doPost(
      HttpServletRequest request, HttpServletResponse response) 
      throws ServletException, IOException {

        processRequest(request, response);
    }
}

This servlet is the controller of our web application.

这个Servlet是我们网络应用的控制器。

First, it reads a parameter id from the request. If the id is submitted, a Student object is fetched from the business layer.

首先,它从请求中读取一个参数id。如果id被提交,就会从业务层获取一个Student对象。

Once it retrieves the necessary data from the Model, it puts this data in the request using the setAttribute() method.

一旦它从模型中检索到必要的数据,它就会使用setAttribute()方法将这些数据放到请求中。

Finally, the Controller forwards the request and response objects to a JSP, the view of the application.

最后,控制器将请求和响应对象转发给JSP,即应用程序的视图。

Next, let’s write our presentation layer student-record.jsp:

接下来,让我们编写我们的演示层student-record.jsp

<html>
    <head>
        <title>Student Record</title>
    </head>
    <body>
    <% 
        if (request.getAttribute("studentRecord") != null) {
            Student student = (Student) request.getAttribute("studentRecord");
    %>
 
    <h1>Student Record</h1>
    <div>ID: <%= student.getId()%></div>
    <div>First Name: <%= student.getFirstName()%></div>
    <div>Last Name: <%= student.getLastName()%></div>
        
    <% 
        } else { 
    %>

    <h1>No student record found.</h1>
         
    <% } %>	
    </body>
</html>

And, of course, the JSP is the view of the application; it receives all the information it needs from the Controller, it doesn’t need to interact with the business layer directly.

当然,JSP是应用程序的视图;它从控制器接收所有需要的信息,它不需要直接与业务层交互。

4. Conclusion

4.结论

In this tutorial, we’ve learned about the MVC i.e. Model View Controller architecture, and we focused on how to implement a simple example.

在本教程中,我们已经了解了MVC即模型-视图-控制器的架构,我们重点讨论了如何实现一个简单的例子。

As usual, the code presented here can be found over on GitHub.

像往常一样,这里介绍的代码可以在GitHub上找到over