1. Understanding MVC
MVC is a classical design pattern, named Model-View-Controller, that is, Model-View-Controller.
Among them, the model is a carrier for encapsulating data, for example, in the Java Usually through a simple POJO (Plain Ordinary) Java Object) to indicate that its essence is ordinary java Bean, which contains a series of member variables and their getter/setter methods. For views, it is more focused on presentation, that is to say, views determine what the interface looks like. In Java, JSP can be used as a view, or through pure HTML, the latter is the current mainstream. Models and views need to be glued by controllers, for example, when a user sends an HTTP request, the request first enters the controller, then the controller obtains data and encapsulates it as a model, and finally the model is transmitted to the view for presentation.
In summary, the interaction process of MVC is shown in Figure 1.
2. Advantages and disadvantages of MVC model
MVC model was born in the 1970s, and it still exists today. It shows that the vitality of MVC model is quite strong. MVC pattern was first used in Smalltalk language, and finally it has been well applied in many other development languages, such as Struts in Java, Struts in Java, etc. spring MVC and other frameworks. It is precisely because of the emergence of these MVC frameworks that the MVC model really landed, making development more efficient, making code coupling as small as possible, and making the responsibilities of various parts of the application more clear.
Since the MVC model is so good, is it not inadequate? I think MVC has at least three shortcomings:
- Each request must go through the process of "Controller - > Model - > View" before the user can see the final interface, which seems to be somewhat complicated.
- In fact, views depend on models. In other words, without models, views can not show the final effect.
- The rendering process of view is accomplished on the server side, and the view page with model is presented to the browser, so the performance can not be well optimized.
In order to make the data presentation process more direct and provide a better user experience, it is necessary to improve the MVC model. Let's try this, first send AJAX request from the browser, then the server accepts the request and returns JSON data to the browser, and finally render the interface in the browser.
The improved MVC pattern is shown in Figure 2.
That is to say, we input AJAX requests and output JSON data. Is there any technology on the market to implement this function? The answer is REST.
The full name of REST is Representational State Transfer. It is a piece about software written by Dr. Roy Fielding in 2000. Framework Style of the paper, this article, Megatron Quartet! Many well-known Internet companies at home and abroad have begun to adopt this lightweight Web service, which is customarily called RESTful. Web Services, or REST Services for short. ]
If the browser side is regarded as the front end and the server side as the back end, the improved MVC mode can be simplified to the following front-end and back-end separation mode, as shown in Figure 3.
Obviously, with REST services, the front-end focuses on the interface display, the back-end focuses on business logic, a clear division of labor, clear responsibilities. So how do you use REST services to separate the front and back ends of your application? Let's move on. First of all, we need to recognize REST.
3. Understanding REST
REST is essentially a way of accessing resources using URLs. As we all know, URL is the request address that we usually use. It includes two parts: request mode and request path. GET and POST are the common request modes, but several other types of request modes are put forward in REST, which can be summarized into six types: GET, POST, PUT, DELETE, HEAD and OPTIONS. Especially the first four operations correspond to CRUD (Create-Retrieve-Update-Delete), such as GET (Check), POST (Add), PUT (Change), DELETE (Delete). These are the similarities and differences between REST and CRUD. It needs to be emphasized that REST is "resource-oriented". The resources mentioned here are actually domain objects, which we often call domain objects. In the process of system design, we often use domain objects to model data.
REST is a "stateless" architecture mode, because at any time the client can send a request to the server, and eventually return the data they want, the current request will not be affected by the previous request. That is to say, the server publishes REST services with internal resources, and the client accesses these resources through the URL. Isn't that the idea of "service-oriented" advocated by SOA? Therefore, REST is also regarded as a "lightweight" SOA implementation technology, so it has been widely used in enterprise applications and Internet applications.
Let's give a few examples to briefly describe REST requests:
It can be seen that the request path is the same, but the request way is different, and the business operation represented is also different. For example, / advertiser/1 request, with GET, PUT, DELETE three different request ways, corresponds to three different business operations.
Although REST seems simple, we often need to provide a REST framework to implement front-end and back-end decoupling architecture, so that developers can focus on business rather than on specific technical details. Next we will use Java technology to implement this REST framework, which will be developed based on Spring.
4. Implementing REST Framework
4.1 Unified Response Structure
Using REST framework to implement front-end and back-end decoupling architecture, we need to first determine that the JSON response structure returned is uniform, that is to say, each REST request will return the same JSON response structure. We may define a relatively general JSON response structure, which contains two parts: metadata and return value, in which metadata indicates whether the operation is successful or not and return value message, and return value corresponds to the data returned by the server-side method. The JSON response structure is as follows:
In order to map the JSON response structure above in the framework, we need to write a Response class corresponding to it:{ "meta": { "success": true, "message": "ok" }, "data": ... }
- public class Response {
- private static final String OK = "ok";
- private static final String ERROR = "error";
- private Meta meta;
- private Object data;
- public Response success() {
- this.meta = new Meta(true, OK);
- return this;
- }
- public Response success(Object data) {
- this.meta = new Meta(true, OK);
- this.data = data;
- return this;
- }
- public Response failure() {
- this.meta = new Meta(false, ERROR);
- return this;
- }
- public Response failure(String message) {
- this.meta = new Meta(false, message);
- return this;
- }
- public Meta getMeta() {
- return meta;
- }
- public Object getData() {
- return data;
- }
- public class Meta {
- private boolean success;
- private String message;
- public Meta(boolean success) {
- this.success = success;
- }
- public Meta(boolean success, String message) {
- this.success = success;
- this.message = message;
- }
- public boolean isSuccess() {
- return success;
- }
- public String getMessage() {
- return message;
- }
- }
- }
Many problems need to be considered to implement the REST framework, and the first one is the problem of object serialization.
4.2 Implementing Object Serialization
Want to explain what object serialization is? It may be illustrated by some examples. For example, a normal HTTP request is sent through a browser, which carries a parameter in JSON format. On the server side, the JSON parameter needs to be converted into a normal Java object. This conversion process is called serialization. For example, when data is retrieved on the server side, the data is a normal Java object, and then the Java object needs to be converted into a JSON string and returned to the browser for rendering. This conversion process is called deserialization. Whether serialization or deserialization, we generally call it serialization.
In fact, Spring MVC has provided us with such serialization features, just using the @RequestBody annotation in Controller's method parameters to define parameters that need to be deserialized, such as the following code snippets:
- @Controller
- public class AdvertiserController {
- @RequestMapping(value = "/advertiser", method = RequestMethod.POST)
- public Response createAdvertiser(@RequestBody AdvertiserParam advertiserParam) {
- ...
- }
- }