The separation of front and back ends has become the mainstream of the industry. In the era of heavy traffic, the emergence of micro-services makes the separation of front and back ends develop more rapidly. The rapid development of front-end frameworks vue.js and Angura. js also speeds up the separation trend.

My official account: MarkerHub, Java website: Markerhub.com

For more selected articles, please click: Java Notes Complete.md


The author | was far broadly

Source | www.blog.csdn.net/weixin_3753…

One, foreword

“Front and back end separation” has become the industry benchmark of Internet project development, effectively decouple through Tomcat+Ngnix(it can also have a Node.js in the middle). In addition, the separation of the front and back ends will lay a solid foundation for the future large-scale distributed architecture, elastic computing architecture, micro-service architecture, multi-terminal services (multiple clients, such as: browser, vehicle-mounted terminals, Android, IOS, etc.).

The core idea of front-end and back-end separation (decoupling) is that the front-end Html page invokes the RestFul API of the back-end through Ajax and interacts with Json data.

Note: In Internet architecture, Web server: generally refers to servers such as Nginx, Apache, they can only parse static resources. Generally speaking, servers such as Tomcat, Jetty and resin can resolve dynamic and static resources, but the ability to resolve static resources is not as good as web server.

Generally, only the Web server can be accessed from the Internet, and only the application server can be accessed from the Intranet.

Why are the front and back ends separated

Generally, the back-end developers of the company directly take into account the front-end work, while implementing THE API interface, while developing the page, the two switch to do each other, and dynamically splicing the page according to different URLS, which also leads to the development pressure of the background greatly increased. Unequal distribution of work at the front and back ends. Not only is development slow, but the code is hard to maintain.

If the front and back ends are separated, the problem of uneven division of labor between the front and back ends can be solved well. More interactive logic is assigned to the front end to deal with, while the back end can focus on its own work, such as providing API interfaces, carrying out permission control and computing. Front-end developers can use NodeJS to build their own local servers, develop directly locally, and then use plug-ins to forward API requests to the background, so that the scene can be completely simulated online and decouple from the background. The front-end can independently complete the whole process of user interaction, both can be started at the same time, not dependent on each other, faster development efficiency, and more balanced division of labor.

Separation from MVC to front and back end

MVC is a classic design pattern. Its full name is Model-view-Controller, that is, model-View-Controller.

Where a model is a vehicle for encapsulating data, for example, typically represented in Java by a simple POJO (Plain Ordinary Java Object), which is essentially a Plain Java Bean, Contains a list of member variables and their getters/setters. In the case of views, it is more presentative, that is, the view determines what the interface will look like, and can be represented in Java as a view through JSP, or presented in pure HTML, which is the current mainstream. The model and view need to be glued together by the controller. For example, if a user sends an HTTP request, the request first goes to the controller, the controller retrieves the data and encapsulates it as a model, and finally the model is passed to the view for presentation.

To sum up, the INTERACTION process of MVC is shown in the figure below:

In other words, we input AJAX requests and output JSON data. Is there any technology on the market that can do this? The answer is REST.

REST stands for Representational State Transfer, a highly publicizing paper written in 2000 by Dr. Roy Fielding on software architectural styles. Many well-known Internet companies at home and abroad have begun to use this lightweight Web Services, we used to call it RESTful Web Services, or REST Services for short.

If you treat the browser side as the front end and the server side as the back end, you can simplify the improved MVC pattern to the following front-end separation pattern:

It can be seen that with REST services, the front end focuses on interface presentation, and the back end focuses on business logic, with clear division of labor and clear responsibilities.

4. Understand Rest architecture

REST is essentially a way to access resources using urls. As we all know, THE URL is the usual use of the request address, which includes two parts: the request mode and the request path, the more common request mode is GET and POST, but in REST also proposed several other types of request, summarized there are six: GET, POST, PUT, DELETE, HEAD, OPTIONS.

The first four, in particular, correspond exactly to the four OPERATIONS of CRUD (create-retrieve-update-delete, add, Delete, modify and search), for example, GET (search), POST (add), PUT (change), Delete (Delete), which is exactly the beauty of REST and CRUD. It is important to note that REST is “resource-oriented,” and the resources mentioned here are actually domain objects, which are often used to model data during system design.

REST is a “stateless” architectural pattern, because at any time a client can make a request to the server and eventually return the desired data, the current request is not affected by the last request. In other words, the server publishes internal resources to REST services, and the client accesses these resources through urls. Isn’t this the idea of “service orientation” advocated by SOA? As a result, REST is also considered a “lightweight” SOA implementation technology and is therefore widely used in both enterprise and Internet applications.

Here are a few examples to briefly describe REST requests:

The same request path but different request modes represent different service operations. For example, the /advertiser/1 request has three different request modes: GET, PUT, and DELETE, which correspond to different service operations.

While REST may seem simple, it is often necessary to provide a REST framework that separates the architecture from the front and back, allowing developers to focus on the business rather than the technical details.

5. Is the separation of front and rear ends significant?

1. The front end of the website changes much more frequently than the back end, which is of great significance.

2, the website is still in the original development mode, data logic and performance logic is mixed, it is significant.

3. The front-end team and back-end team of the website belong to two leadership groups, and the skill points are very different, so it is of great significance.

4, the site front-end effect gorgeous/cross-device compatibility requirements are high, it is significant.

Vi. Specialization (developer separation)

Most of the previous JavaWeb projects were Java programmers working on both the front end (Ajax /jquery/ JS/HTML/CSS etc.) and the back end (Java /mysql/ Oracle etc.).

With the development of The Times, gradually many small and medium-sized companies began to put the boundaries of the front and back end more and more clear, front-end engineers only front-end things, back-end engineers only back-end things.

Is the so-called specialty, if a person can do anything, so he is not good at anything after all.

Large and medium-sized companies need professionals, small companies need generalists, but for individual career development, I recommend separate.

For backend Java engineers:

Focus on Java fundamentals, design patterns, JVM principles, Spring + Spring MVC principles and source code, Linux, mysql transaction isolation and locking mechanism, mongodb, HTTP/TCP, multi-threading, distributed architecture (Dubbo, Dubbox, Spring Cloud), elastic computing architecture, microservices architecture (SpringBoot + ZooKeeper + Docker + Jenkins), Java performance optimization, and related project management, etc.

The back end pursues the three high points (high concurrency, high availability, high performance), security, storage, business, and so on.

For front end engineers:

Focus on HTML5, CSS3, jquery, AngularJS, Bootstrap, ReactJS, Vuejs, Webpack, less/sass, gulp, NodeJS, Google V8, javascript multi-threading, modular, Faceted programming, design patterns, browser compatibility, performance optimization, and more.

The front-end is about page performance, speed, compatibility, user experience, and so on.

Tips: You can follow the wechat official account: Java backend, get more excellent blog push.

7. Coupling era

There was a time when our JavaWeb projects used several backend frameworks, SpringMVC/Struts + Spring + Spring JDBC/Hibernate/Mybatis, etc.

Most projects have three layers on the Java back end: a control layer (Controller/Action), a business layer (Service/Manage), and a persistence layer (DAO).

The control layer is responsible for receiving parameters, calling relevant business layers, encapsulating data, and routing & rendering to JSP pages.

Then JSP page using a variety of tags (JSTL/EL/Struts tags, etc.) or handwritten Java expressions (<%=%>) will show the background data, play is MVC that set of ideas.

Let’s look at the situation: requirements are finalized, code is written, tests are tested, and then what? Ready to launch?

You need to use maven and eclipse tools put your code into a war file, and then the war file to your production environment of the web container (tomcat/jboss, weblogic/websphere/jetty/resin), right?

Once you’re done publishing, you need to start your Web container and start providing services, at which point you’ll be able to access your site (assuming you’re a website) by configuring the domain name, DNS, etc.

Is your front and back end code all in that WAR package? That includes your JS, your CSS, your images, all kinds of third-party libraries, right?

Ok, now enter your web domain name (www.xxx.com) in your browser. What happens? (This question is also asked at many companies.)

I picked up the dry said ah, the foundation of poor children’s shoes please go to search.

The browser finds the external IP of your server through the domain name and sends the HTTP request to your server. After the tcp3 handshake (TCP/IP is below HTTP), the data starts to be transmitted through TCP protocol. After your server gets the request, it starts to provide services and receive parameters. It then returns your response to the browser, which parses it through the Content-Type and renders it to the user.

So let’s say you have 100 images on your home page, and what looks like an HTTP request from the user is not a single HTTP request, and when the user visits for the first time, there’s no cache in the browser, and your 100 images, The browser has to make HTTP requests 100 times in a row (someone will tell me the HTTP connection problem is not discussed here), and your server needs to consume memory to create sockets to play with TCP transfers (consuming computing resources on your server).

Key here, in this case, the pressure of your server will be very big, because the page of all the requests are only request to you on this server, if one is good, if 10000 individual concurrent access (first not to chat server cluster, there is a single instance server), that you of how much server can resist a TCP connection? How much bandwidth do you have? How much memory does your server have? Is your hard drive high-performance? How much IO can you hold? How much memory do you assign to the Web server? Will it go down?

That’s why, the larger the medium to large web applications, the more decoupled they are.

Theoretically you can put your database + application service + message queue + cache + files uploaded by users + log + and so on on a server, you don’t have to play what service governance, also don’t have to do what performance monitoring, what alarm mechanism, etc., just a mess.

But it’s like putting all your eggs in one basket, and it can be very dangerous. If the entire server runs out of memory due to memory instability in one of the sub-applications, your entire site is down.

If there is an accident, and your business is in the peak period of blowout development, then congratulations, business success is stuck by technology, it is likely to lose a large number of users, the consequences are unimaginable. Note: Technology has to be ahead of the business, or you will miss out on the best growth.

In addition, all of your application are coupled together, the equivalent of a boulder, when the server load capacity is insufficient, typically using load balanced approach, the server cluster, so that you are in a horizontal extension pieces of rock, the acceleration performance will be more and more low, you know, itself the function of the load is low or module is not necessary to scale, The example in this article is that your performance bottleneck is not in the front end, so why extend the front end horizontally? And when the release deployment went online, I clearly only changed the back-end code, why do I want to release the front-end as well?? (Quote: Architecture Adventures – Lightweight Microservices Architecture, Yong Huang)

Normal Internet architecture, is to be dismantled, your Web server cluster, your application server cluster + file server cluster + database server cluster + message queue cluster + cache cluster and so on.

JSP pain points

Layer before most of the use of JSP javaWeb project as a page display data to the user, because the traffic is not high, so it is less demanding performance requirements, but now is the era of big data, for the performance requirements of the Internet project is more and more high, so the original front end coupling together of architectural pattern has gradually can not meet us, So we need to find a decoupled way to dramatically increase our load capacity.

1, dynamic resources and static resources are all coupled together, the server is under great pressure, because the server will receive various HTTP requests, such as CSS HTTP requests, JS, images and so on.

Once the server is in trouble, the front and back end play together, and the user experience is terrible.

2. After the UI has a good design drawing, the front-end engineer is only responsible for cutting the design drawing into HTML, which needs to be set into JSP pages by Java engineers. The error rate is high (because a large number of JS codes often appear in the page).

3, JSP must be run in Java support web server (such as Tomcat, Jetty, resin, etc.), can not use Nginx, etc. (Nginx is said to single instance HTTP concurrency up to 5W, this advantage should be used), performance can not be improved.

4. The first request for a JSP must be compiled into a servlet in the Web server, which will run slower the first time.

  1. Each JSP request is an HTML page that accesses the servlet output stream, which is not as efficient as using HTML directly.

JSP has so many tags and expressions that the front-end engineer will be overwhelmed and encounter many pain points when modifying the page.

7. If the JSP has a lot of content, the page response will be slow because it is loaded synchronously.

8, the need for front-end engineers to use Java IDE (such as Eclipse), as well as the need to configure a variety of back-end development environment, you have considered the experience of front-end engineers.

Based on some of the pain points mentioned above, we should move the development weight of the entire project forward to achieve true decoupling of the front and back ends!

Development mode

The old way was:

  • Product experience/leader/customer requirements

  • The UI makes the design

  • Front-end engineers do HTML pages

  • The backend engineer will set HTML pages into JSP pages (the back and back end is strongly dependent, the back end must wait for the front-end HTML to do a good job to set JSP. If the HTML changes, it’s even more painful and inefficient.)

  • Integration failure

  • The front-end rework

  • After the rework

Secondary integration

Integration success

delivery

The new approach is:

  • Product experience/leader/customer requirements

  • The UI makes the design

  • Front and back end conventions interface & data & parameters

  • Parallel development at the front and back ends (no strong dependence, parallel development at the front and back ends, if the requirements change, as long as the interface and parameters remain unchanged, there is no need to modify the code on both sides, high development efficiency)

  • Front end integration

  • Front-end page adjustment

  • Integration success

  • delivery

Request way

The old way was:

  • Client request

  • Servlets or controllers on the server side receive requests (the back-end controls the routing and rendering of the page, with most of the weight of the overall project development on the back-end)

  • The Service is called and the DAO code completes the business logic

  • Return to the JSP

  • The JSP presents some dynamic code

The new approach is:

  • Browser sends request

  • Direct to THE HTML page (front end controls routing and rendering page, weight of whole project development moves forward)

  • The HTML page is responsible for generating data by calling the server-side interface (via Ajax, etc., and returning data in JSON format in the background, which replaces XML for its simplicity and efficiency)

  • Populate HTML, display dynamic effects, parse and manipulate the DOM on the page.

(Interested children can visit alibaba and other large sites, and then click F12, monitor how you refresh the page, its HTTP play, most of them are separate requests for background data, using JSON data transmission, Rather than one big, complete HTTP request that returns the entire page, including both dynamic and static.)

To summarize the new approach to request steps:

Large number of concurrent browser requests –> Web Server Cluster (NGINx)– > Application Server Cluster (Tomcat)– > File/database/cache/message queue server cluster

At the same time, it can be divided into modules and divided into small clusters according to business to prepare for the later architecture upgrade.

The advantages of front and back separation

1. Real front-end and back-end decoupling can be achieved, with the front-end server using NGINx.

The front-end/WEB server puts a series of static resources such as CSS, JS, images and so on (you can even put CSS, JS, images and other resources into a specific file server, such as ALI Cloud OSS, and use CDN acceleration). The front-end server is responsible for controlling page reference & jump & routing. The front-end page asynchronously calls the back-end interface, and the back-end/application server uses Tomcat (think of it as a data provider) to speed up the overall response.

Use front-end engineering frameworks such as NodeJS, React, Router, React, Redux, and Webpack

2, find the bug, can quickly locate who is the problem, there will be no mutual kicking phenomenon.

Page logic, jump errors, browser compatibility issues, scripting errors, page styles, etc., are all the responsibility of the front-end engineer.

Problems such as interface data error, data submission failure, and reply timeout are all solved by back-end engineers.

The two sides do not interfere with each other, and the front end and back end are a loving family.

3. In the case of large concurrency, I can expand the front and back end servers horizontally at the same time. For example, a home page of Taobao needs 2000 + front-end servers as a cluster to resist the daily pv of hundreds of millions.

Go to ali’s tech summit and hear them write their own web container, even if it has 100 thousand HTTP concurrent instances, 2000 is 200 million HTTP concurrent instances, and they can scale infinitely based on predicted flood peak, horrible, just one home page…

4. Reduce the concurrency/load on the back-end server

All HTTP requests except for the interface are transferred to the front-end Nginx, and the interface requests invoke Tomcat, referring to the Nginx reverse proxy Tomcat.

And the browser makes a lot of calls to the local cache except for the first page request.

5. Even if the back-end service is temporarily timed out or down, the front-end page will be accessed normally, but the data will not be brushed out.

6. Maybe you also need to have a light application related to wechat, so that your interface can be completely shared. If there are also app-related services, then as long as some code reconstruction, you can also reuse a lot of interfaces to improve efficiency. (Multi-terminal application)

7, the page is not afraid to display more things, because it is asynchronous loading.

8, Nginx support page hot deployment, do not need to restart the server, front-end upgrade more seamless.

9. Increase code maintainability & readability (code that is coupled at the front and back ends is quite laborious to read).

10, improve the development efficiency, because the front and back end of parallel development, rather than the previous strong dependency.

11, the deployment of certificates in nginx, the use of HTTPS access to the external network, and only open port 443 and 80, other ports are closed (to prevent hacker port scanning), Intranet use HTTP, performance and security are guaranteed.

A lot of front-end component code to reuse, componentalization, improve development efficiency, out!

Matters needing attention

1. During the requirements meeting, both front and back end engineers must attend and develop interface documents. Back end engineers should write test cases (2 dimensions). Test cases for the Service layer are written in junit. Ps: Can you play unit tests on the front end?

The above interface is not the Java interface, so call the method in your controler.

3. Increased the workload of the front-end team, reduced the workload of the back-end team, and improved performance and scalability.

4, we need some front-end framework to solve the functions like page nesting, paging, page jump control and so on. (Those front-end frameworks mentioned above).

5. If your project is small, or if it’s purely an Intranet project, you can rest assured that you don’t need any architecture, but if your project is an extranet project, hehe.

6. In the past, some people have used template frameworks such as Velocity/Freemarker to generate static pages.

7, the main purpose of this article is to say that JSP in the large external Java Web project has been eliminated, but did not say that JSP can be completely not learn, for some students, JSP /servlet and other related Java Web foundation or to master the firm. What else do you think a framework like SpringMVC is based on?

8. If the page has some permissions and other related validation, the related data can also be retrieved from the interface via Ajax.

For both front-end and back-end logic, I recommend putting it in the front end, why?

Since your logic requires computing resources to compute, if you run your logic in the back end, it will consume bandwidth, memory, CPU, etc. You should remember one thing: The server side has limited computing resources, and if you put it in the front end and use the client side’s computing resources, your server side load will decrease (high concurrency scenario).

Similar to data verification, both the front and back end need to do!

10, the front end needs to have a mechanism to deal with the back-end request timeout and back-end service downtime, friendly display to the user.

Further reading

1. In fact, static resources such as JS, CSS and pictures can be considered in the OSS file server similar to Ali Cloud (if it is an ordinary server & operating system, stored in the file after reaching the PB level, or the number of files in a single folder reaches 30,000 to 50,000, IO will have serious performance problems). With CDN (national child Node Acceleration) on OSS, your pages will fly no matter where you are in the country, and your Nginx load will be further reduced.

2. If you want to play with a lightweight microservice architecture and use NodeJS as a gateway, the benefits of using NodeJS are also beneficial for SEO optimization, because Nginx only returns static resources to the browser, while domestic search engine crawlers only grab static data and do not parse THE JS in the page. This makes the application poorly supported by search engines. Also, because Nginx does not do page assembly rendering, the static page needs to be returned to the browser and rendered, which increases the rendering burden of the browser.

Requests initiated by the browser are distributed through Nginx, and URL requests are uniformly distributed to NodeJS for page assembly and rendering. API requests are sent directly to the back-end server to complete the response.

3. If you encounter cross-domain problems, Spring4’s CORS can be perfectly solved, but there are generally no cross-domain problems using nginx reverse proxy, unless you split the front-end and back-end services into two domains. The JSONP approach is also obsolete.

4, If you want to play multiple applications, pay attention to remove the tomcat native session mechanism, use the token mechanism, use caching (because it is a distributed system), do a single point, for the security of the token mechanism, you can search JWT.

5. Mock tests can be added to the front-end project (virtual test objects can be constructed to simulate the back-end, which can be independently developed and tested). The back-end needs detailed test cases to ensure the availability and stability of the service.

conclusion

Front-end separation is not just a development pattern, but an architectural pattern (front-end separation architecture).

Don’t think that separating the front end from the back end means separating the front end from the back end. You need to distinguish between the front and back end projects. Front-end and back-end projects are two projects, on two different servers, deployed independently, two different projects, two different code bases, and different developers.

The front and back end engineers need to agree interaction interfaces to achieve parallel development. After development, they need to deploy independently. The front end invokes HTTP requests through Ajax and invokes restful apis at the back end.

The front end only needs to focus on page style and dynamic data parsing & rendering, while the back end focuses on concrete business logic.