mvc设计模式_MVC设计模式

mvc设计模式

MVC Design Pattern is one of the oldest architectural pattern for web applications. MVC stands for Model View Controller. MVC Design Pattern is used to separate the logic of different layers in a program in independent units. This is known as the principle of Separation of Concern.

MVC设计模式是Web应用程序中最古老的体系结构模式之一。 MVC代表模型视图控制器。 MVC 设计模式用于以独立单位将程序中不同层的逻辑分开。 这被称为关注点分离原则。

MVC设计模式 (MVC Design Pattern)

With MVC design pattern, we have following components on which our design depends:

使用MVC设计模式,我们具有设计所依赖的以下组件:

  • The model which is transferred from one layer to the other.

    从一层转移到另一层的模型。
  • The View which is responsible to show the data present in the application.

    视图负责显示应用程序中存在的数据。
  • The controller is responsible to accept a request from a user, modify a model and send it to the view which is shown to the user.

    控制器负责接受来自用户的请求,修改模型并将其发送到显示给用户的视图。

The idea behind MVC pattern is a very clear separation between domain objects which represents real-world entities and the presentation layer we see on the screen. Domain objects should be completely independent and should work without a View layer as well.

MVC模式背后的思想是,在代表真实世界实体的域对象和我们在屏幕上看到的表示层之间非常清晰地分离。 域对象应完全独立,并且也应在没有View层的情况下工作。

In this lesson, we will try to establish a strong MVC example with a Spring Boot application which uses Thymeleaf in the View layer.

在本课程中,我们将尝试使用Spring Boot应用程序在View层中使用Thymeleaf建立一个强大的MVC示例。

MVC应用架构 (MVC Application Architecture)

Before we start building our application, it is always a good idea to structure it. Based on the MVC pattern, we will have following layers in our application:

在开始构建应用程序之前,构建结构始终是一个好主意。 基于MVC模式,我们的应用程序中将包含以下几层:

MVC模式示例 (MVC Pattern Example)

As we will build a Spring Boot application based on MVC pattern, we start by making a Maven based project and added Spring Boot related dependencies to it.

当我们将基于MVC模式构建Spring Boot应用程序时,我们首先创建一个基于Maven的项目,并向其中添加与Spring Boot相关的依赖项。

<parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-parent</artifactId>
  <version>1.5.7.RELEASE</version>
  <relativePath/> <!-- lookup parent from repository -->
</parent>

<properties>
  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
  <java.version>1.8</java.version>
</properties>

<dependencies>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
  </dependency>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
  </dependency>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
  </dependency>
  <dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <scope>runtime</scope>
  </dependency>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
  </dependency>
</dependencies>

<build>
  <plugins>
    <plugin>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-maven-plugin</artifactId>
    </plugin>
  </plugins>
</build>

Now, let’s start by defining our model.

现在,让我们开始定义模型。

MVC模型 (MVC Model)

Let’s start defining the pieces and move with our model first. The first step for a sample app is defining our Model class:

让我们开始定义各个部分并首先使用我们的模型。 示例应用程序的第一步是定义我们的M odel类:

package com.journaldev.mvcpattern.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity
public class Person {

    @Id
    @GeneratedValue
    private Long id;
    private String name;
    private int age = 0;

    //standard getters and setters
}

This is a simple model class which can contain a Person’s information. Let’s use the defined model in our Controller and Service.

这是一个简单的模型类,可以包含一个人的信息。 让我们在Controller and Service中使用定义的模型。

MVC控制器 (MVC Controller)

Now that we know what data to transmit in Model, let us define a Controller to allow user to request this data:

现在我们知道要在Model中传输什么数据,让我们定义一个C ontroller以允许用户请求此数据:

package com.journaldev.mvcpattern.controller;

import com.journaldev.mvcpattern.model.Person;
import com.journaldev.mvcpattern.service.PersonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class PersonController {

    @Autowired
    PersonService personService;

    @RequestMapping(value = "", method = RequestMethod.GET)
    public String greetingForm(Model model) {
        model.addAttribute("person", new Person());
        return "greeting";
    }

    @RequestMapping(value = "/person", method = RequestMethod.POST)
    public String addPerson(Model model, @ModelAttribute Person person) {
        personService.createPerson(person);
        model.addAttribute("people", personService.getAllPersons());
        return "result";
    }
}

In the controller above, we defined two APIs:

在上面的控制器中,我们定义了两个API:

  1. The base URL of the application presents a simple View we design next.

    该应用程序的基本URL展示了一个我们接下来设计的简单视图。
  2. The /person URL of the application presents a simple View which tabulates the person data.

    应用程序的/person URL提供一个简单的视图,该视图将人员数据制成表格。

We will see the Views in a minute. Before that, we need to provide the Service and Repository layer as well.

我们将在一分钟内看到“视图”。 在此之前,我们还需要提供服务和存储库层。

package com.journaldev.mvcpattern.service;

import com.journaldev.mvcpattern.model.Person;
import java.util.List;

public interface PersonService {
    Person createPerson(Person person);
    List<Person> getAllPersons();
}

The interface implementation looks like:

接口实现如下所示:

package com.journaldev.mvcpattern.service;

import com.journaldev.mvcpattern.dal.PersonRepository;
import com.journaldev.mvcpattern.model.Person;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class PersonServiceImpl implements PersonService {

    @Autowired
    private PersonRepository personRepository;

    @Override
    public Person createPerson(Person person) {
        return personRepository.save(person);
    }

    @Override
    public List<Person> getAllPersons() {
        return personRepository.findAll();
    }
}

Finally, The DAL layer, the repository interface looks like:

最后,在DAL层中,存储库接口如下所示:

package com.journaldev.mvcpattern.dal;

import com.journaldev.mvcpattern.model.Person;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface PersonRepository extends JpaRepository<Person, Long> {
}

Excellent! Now that we’re done with the all the service and DB access logic, we can finally try our View.

优秀的! 既然我们已经完成了所有服务和数据库访问逻辑,那么我们终于可以尝试使用View了。

MVC视图 (MVC View)

Let’s finally put our View in place. We first define our greetings.html page in src/main/resources/templates directory.

最后,我们将视频放置到位。 我们首先在src/main/resources/templates目录中定义greetings.html页面。

<!DOCTYPE HTML>
<html xmlns:th="https://www.thymeleaf.org">
<head>
    <title>Spring Boot MVC</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>
<body>
<h1>Add new person</h1>
<form action="#" th:action="@{/person}" th:object="${person}" method="post">
    <p>Name: <input type="text" th:field="*{name}"/></p>
    <p>Age: <input type="number" th:field="*{age}"/></p>
    <p><input type="submit" value="Submit"/> <input type="reset" value="Reset"/></p>
</form>
</body>
</html>

Next, we define our result.html page as well:

接下来,我们还定义了result.html页面:

<!DOCTYPE HTML>
<html xmlns:th="https://www.thymeleaf.org">
<head>
    <title>Spring Boot MVC</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>
<body>
<div th:if="${not #lists.isEmpty(people)}">
    <h2>Person List</h2>
    <table class="glyphicon glyphicon-calendar">
        <tr>
            <th>Id</th>
            <th>Name</th>
            <th>Age</th>
        </tr>
        <tr th:each="person : ${people}">
            <td th:text="${person.id}"></td>
            <td th:text="${person.name}"></td>
            <td th:text="${person.Age}"></td>
        </tr>
    </table>
</div>
</body>
</html>

MVC模式测试 (MVC Pattern Test)

Now, we can finally run our application to see it in action. But the application was not the focus here. Focus was to keep the three components completely separate which was excellent to observe. However, below images show the project output.

现在,我们终于可以运行我们的应用程序,以查看其运行情况。 但是应用程序不是这里的重点。 重点是使这三个组件完全分开,这非常好观察。 但是,下面的图像显示了项目输出。

MVC设计模式的优势 (Advantages of MVC Design pattern)

There are many advantages for using MVC pattern. Let’s state some of them here:

使用MVC模式有很多优点。 让我们在这里声明其中一些:

  1. MVC allows rapid application development. If we simply define the Model layer in advance and pass this information to UI development team, they can start making the Views in paralles as Backend developers design the application Controllers and logic behind them resulting in faster development.

    MVC允许快速的应用程序开发。 如果我们简单地预先定义模型层,并将此信息传递给UI开发团队,那么当后端开发人员设计应用程序Controllers及其背后的逻辑时,他们便可以并行创建Views,从而加快了开发速度。
  2. While changing a View mechanism, Controller layer doesn’t even have to know where the data goes. It only knows a logical view name and not even the HTML extension. So, it is very easy to switch to an Angular based view without affecting the Controller.

    在更改视图机制时,控制器层甚至不必知道数据的去向。 它只知道逻辑视图名称,甚至不知道HTML扩展名。 因此,在不影响Controller的情况下切换到基于Angular的视图非常容易。
  3. MVC pattern emphasis on the low coupling between different components of an application. So, the View layer have no dependency on service layer and only Controller depends on it, even that with the interfaces and not from concrete implementation.

    MVC模式强调应用程序不同组件之间的低耦合。 因此,View层不依赖于服务层,只有Controller依赖于它,即使依赖于接口,也不依赖于具体的实现。

MVC模式结论 (MVC Pattern Conclusion)

In this article, we learned how we can put MVC design pattern to use to emphasize on keeping different layers completely separate and so, our components loosely coupled.

在本文中,我们学习了如何使用MVC设计模式来强调保持不同的层完全分离,从而使我们的组件松散耦合。

Design patterns are just based on a way of programming and so, is language and framework independent. Feel free to leave your views in comments below. Download the MVC example project from the link below.

设计模式仅基于编程方式,因此与语言和框架无关。 请随时在下面的评论中留下您的看法。 从下面的链接下载MVC示例项目。

Reference: Wikipedia

参考: 维基百科

翻译自: https://www.journaldev.com/16974/mvc-design-pattern

mvc设计模式

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值