Separation of front and back development and cross domain problems

Keywords: Java JSON JQuery Mobile

Front and rear end separation

Traditional development mode

Once upon a time, JSP and Servlet brought infinite scenery to Java, which became popular for a while. However, with the continuous development of the Internet, such a development method gradually revealed its disadvantages. In the hot mobile Internet today, the application requirements for background services have changed dramatically;

Traditional project development and interaction process:

In the traditional web development, the content displayed on the page and the jump logic between pages are all controlled by the background, which leads to the high coupling degree between the front and back ends. The high coupling degree means that the scalability is poor, the maintainability is poor, and so on

The problems of traditional development are as follows:

  • High coupling
  • Debugging is troublesome, when there is a problem, the front and back stations are often required to check together

  • Low development efficiency, mutual dependence of front and back ends, high communication cost and maintenance cost
  • Poor scalability, unable to be compatible with other terminals
  • Confusion of interaction logic (remember paging display), resulting in code corruption

In order to adapt to the rapid development of mobile Internet and accelerate the development speed, it is necessary to find a new project development mode to solve the above problems;

Front and rear end separation development mode

The root cause of the above problems is that there is no obvious boundary between the front and back ends, which is seriously coupled. The core to solve these problems is to completely separate the front and back end codes

Separate development and interaction process of front and back end:

Is there anything different?

Compared with the whole project structure and deployment environment we wrote before, there are the following differences

Characteristics / methods tradition Front and rear end separation
Server environment All deployed to tomca Add a static resource server
MVC responsibilities The backstage is responsible for all MVC VC in front, M in back

Simply put:

The separation of front end and back end adds a server to deal with static resources in traditional development. The View layer and Controller layer are put in the front end. The back end only needs to deal with data access and business logic

Front end: responsible for View and Controller layer.

Back end: only responsible for Model layer, business processing / data, etc.

Advantages and disadvantages of front and rear end separation

advantage:

  • Focus separation, view layer and control layer logic moved to the front end, and the back end pays more attention to business logic and system architecture

  • Coupling is greatly reduced, development efficiency and maintenance efficiency are improved

  • Error friendly, background error does not affect the display of front-end interface

  • For developers, the front and back end no longer need too many development languages involving each other

Disadvantages:

  • The front-end developers are under more pressure, so they need to pay attention to the Controller layer
  • After adding static servers, the system structure is more complex
  • More HTTP requests, less efficient on the mobile side
  • The logic is close to the front end, and different platforms need to be targeted and implemented repeatedly, (Android iOS+web)
  • SEO optimization is weak, most crawlers do not support ajax

Redefinition of front and rear end:

Before that, the front and back end are distinguished according to the hardware environment

After separation, according to the division of responsibilities: as shown in the figure

Execution process of front and back page separation (for browser)

In the Controller layer, process control will be used to complete data verification, data analysis, page Jump and other actions, so how to complete it needs to use JavaScript

How does the front end complete the final data display for a project with front-end and back-end separated?

If the front-end is other such as iOS and Android, there is no need to request static pages. The page drawing is implemented by the system's original language, just request json data from the background

what is json?

JSON full name (JavaScript Object Notation),js object representation, is a lightweight data exchange format

characteristic:

  • Simple format
  • Easy to parse, cross platform
  • Lightweight
  • Content is a string

Originally produced in web projects, it was used by various CS structure projects because of its excellence

Case:

{
                "uniquekey":"a56e67162bd84ee9c480e22a1170c14b",
                "title":"Per capita debt: 170000, from "national savings" to "national debt", where is the money of Chinese people?",
                "date":"2019-12-22 13:43",
                "category":"Headlines",
                "author_name":"Hechuan falls into the sea",
                "url":"http://mini.eastday.com/mobile/191222134359221.html",
                "thumbnail_pic_s":"http://05imgmini.eastday.com/mobile/20191222/20191222134359_b6ded6df388f5c6747e67bacfc32d125_4_mwpm_03200403.jpg"
}

You can think of it as a Map data structure, which is stored in the form of key value pairs, but some data structures in java, such as collections, are not available in json

Unsatisfied front-end partners node.js

Now that you know the concept of front-end and back-end separation and the operation process, you can't help but secretly rejoice as a back-end developer. After that, the Controller will not be in my charge. You are about to start Ge You's lie down when the front-end guy is frying pan:

Nima, various page Jump logic, user verification logic, front-end form verification ... do you want to learn java? They are used to js, they certainly don't want to

The problem is power. Ryan Dahl, a brother of foreign countries, decided to change this situation, so he developed Node.js(2009/5), which uses JS as the development language, providing asynchronous IO, database support, network support, and so on. The majority of front-end developers burst into tears, and don't deal with java in the future. The front-end and back-end sets of JS are all completed, and the dream is beautiful. java(1996) is powerful, and has gone through more than 20 years of efforts AVA is already so powerful and stable. Node.js, as a late show 13 years later, has a long way to go;

I believe that the day of writing all programs in one language will come, and many people are trying to realize this dream, such as RectNative;

The role of Node.js in front and back end separation

As we all know, Taobao website faces hundreds of front-end pages. If we want to improve the overall development efficiency and project scalability, we must adopt the front-end separation, a large number of Controller layer logic and data verification logic, which leads to the front-end development of Alexandria, and there is no relatively fixed development model, which is very easy to cause problems

At present, Taobao uses an architecture called Midway Island, which uses Node.js to complete the Controller layer and provides some other good features

framework:

duty:

advantage:

  • Request aggregation, Node integrates multiple request responses on the server side, one-time return, higher efficiency
  • SEO optimization
  • JS language, low learning cost
  • Browser and Node.js end code can be reused
  • Server rendering

If it is used as a front-end framework, the comparison between Node.js and Vue.js is undoubtedly of great importance

emphasize:

It is not necessary to add node.js to the front-end and back-end separation. The separation of front-end and back-end is a problem of responsibility division, which has nothing to do with which server to use;

Try it

Use Ajax to request data in the page, the server returns json data, and the front end uses js to complete page rendering

Ajax

Ajax is a client-side request method, full name (Asynchronous Javascript And XML)

It is used to send HTTP requests to the server asynchronously and get response data. The advantage of asynchrony is that the browser will not get stuck during the request, and it can respond to the user's operation normally. Common form submission and direct opening of the specified address are synchronous;

Object to json

The basic form of json data is the key value pair, which corresponds to the attributes in the object and is regular. Then you can use the code to complete the conversion process. Here are some common json open source tools

  • Gson
  • FastJson
  • Jackson
  • Json-lib

See here for performance comparison Contrast

Choose fastjson here

Download jar

http://repo1.maven.org/maven2/com/alibaba/fastjson/

Case:

import com.alibaba.fastjson.JSON;

import java.util.ArrayList;

public class Demo {
    public static void main(String[] args) {
        //Bean knows
        ArrayList<String> hobby = new ArrayList<>();
        hobby.add("girl");
        hobby.add("music");
        hobby.add("coding");

        //JavaBean
        Person p = new Person("jerry",18,true,hobby);
        p.setDog(new Dog("Little flower"));

        //Bean to json string
        String s = JSON.toJSONString(p);
        System.out.println(s);

        //json character to Bean
        Person person = JSON.parseObject(s,Person.class);
        System.out.println(person);

        //ArrAyList to json string
        System.out.println(JSON.toJSONString(hobby));
    }
}

Front and rear end separation cases

Now regard yourself as the front end, and develop a simple page that is separated from the front to the back to display the student information list

First step

Write a static page to show the table

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title></title>

    </head>
    <body>
        <table id="tab" border="1">
            <tr>
                <th>number</th>
                <th>name</th>
                <th>Age</th>
                <th>Gender</th>
            </tr>
        </table>
        <button onclick="req()">Request data</button>
        <img id="img" />
    </body>
</html>

Without launching tomcat, you can access it directly by opening it in the editor, testing that it is a static web page, and our editor is an HTTP server that can respond to the static web page

The second step

Introducing jquery makes ajax writing more convenient

<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>

Step 3

Write ajax and send requests to the server

The fourth step

Show data to page

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title></title>
        <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
    </head>
    <body>
        
        <table id="tab" border="1">
            <tr>
                <th>number</th>
                <th>name</th>
                <th>Age</th>
                <th>Gender</th>
            </tr>
        </table>
        <button onclick="req()">Request data</button>
        <img id="img" />
    </body>
    <script>
        function req(){
            document.getElementById("img").src = "img/timg.gif";
            $.ajax({
                url:"http://localhost:8080/MyServer/getData",
                success:function(data){
                    console.log(data);
                    document.body.insertAdjacentHTML("beforeend","<h1>%</h1>".replace("%",data));
                    document.getElementById("img").src = "";    
                },
                error:function(err){
                    console.log(err);
                    document.getElementById("img").src = "";    
                }
            });
        }
    </script>
</html>

Now the identity switches back to the back end to develop the interface for getting the table data

  1. Create a web project
  2. Create Servlet
  3. Introducing fastjson
  4. Create a bean class
  5. Create a bunch of bean s to put in the list
  6. Turn the list into a json string and return it to the front end

Servlet code

package com.kkb;

import java.io.IOException;

public class AServlet extends javax.servlet.http.HttpServlet {
    protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
    }
    protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
        String s = "{\"name\":\"jack\"}";
        response.getWriter().println(s);
    }
}

Start the service, test the access, and you will find that the results returned by the server are not displayed on the page .

Cross the question

When you open the browser check page, you will find that there is an error message instead of the message returned by the output server. This is the most common cross cutting problem of front-end and back-end separation

What is cross domain

The reason why leapfrogging comes into being is that browsers follow the same origin strategy

Homologous strategy:

The Same origin policy is a kind of convention. It is the core and basic security function of the browser. If the Same origin policy is missing, the normal function of the browser may be affected. It can be said that the Web is built on the basis of the Same origin policy, and the browser is only an implementation of the Same origin policy.

The same origin policy is the behavior of the browser. It is to protect the local data from being polluted by the data acquired by JavaScript code. The browser will send an OPTION request for pre check to determine whether the server allows cross domain. If it allows, the real request will be sent. Otherwise, an exception will be thrown.

Simply put:

The core security mechanism of the same origin policy browser, which does not allow parsing and execution of data from other servers in the page

How to determine whether cross domain

When any one of the protocol, domain name and port of a request url is different from the current page url, it is cross domain

Homology restriction:
  1. Unable to read cookies, LocalStorage and IndexedDB for non homologous web pages

  2. Unable to send AJAX request to non origin address

When cross domain issues arise:

When a browser parses and executes a web page, if the js code in the page requests another non homologous resource, there will be a cross problem

There is no cross domain problem when the browser directly jumps to another non homologous address

Solve the spanning problem

Since the behavior of browser in cross domain problem is prohibited, only the browser needs to be set to run and analyze the data of cross domain request, but this setting must be placed on the server side, and the server side will judge whether the other side can be trusted

Add a field in the response header to tell the browser that a server is trusted

package com.kkb;

import java.io.IOException;

public class AServlet extends javax.servlet.http.HttpServlet {
    protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {

    }

    protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
        response.setHeader("Access-Control-Allow-Origin","*");
        String s = "{\"name\":\"jack\"}";
        response.getWriter().println(s);
    }
}

Its value spans a specified domain name, or * indicates that all addresses are trusted

Other related settings

//Specify allow other domain name access
'Access-Control-Allow-Origin:http://30. XXX. Xxx '/ / general usage (*, specified domain, dynamic setting), note * do not allow to carry authentication header and cookies
//Whether to allow subsequent requests to carry authentication information (cookies). This value can only be true, and the default value is false
//And the front end needs to cooperate with the corresponding settings to make cookie s cross
'Access-Control-Allow-Credentials:true'
//Pre inspection interval
'Access-Control-Max-Age: 1800'
//Allowed request types
'Access-Control-Allow-Methods:GET,POST,PUT,POST'
//List the fields that must be carried
'Access-Control-Allow-Headers:x-requested-with,content-type'

After solving the spanning problem, we can improve the above case

Servlet Code:
package com.kkb;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.io.IOException;
import java.util.ArrayList;

public class AServlet extends javax.servlet.http.HttpServlet {
    protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {

    }

    protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
        //Allow cross access from any host
        response.setHeader("Access-Control-Allow-Origin","*");
                //Set the response type to json data
        response.setContentType("application/json;charset=utf-8");

        //Student information
        ArrayList<Student> students = new ArrayList<>();

        Student stu1 = new Student("s1","jack",20,"man");
        Student stu2 = new Student("s2","tom",22,"girl");
        Student stu3 = new Student("s3","jerry",10,"woman");
        Student stu4 = new Student("s4","scot",24,"boy");
        students.add(stu1);
        students.add(stu2);
        students.add(stu3);
        students.add(stu4);
        response.getWriter().println(JSON.toJSONString(JSON.toJSONString(students)));
    }
}
HTML code
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title></title>
        <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
    </head>
    <body>
        <table id="tab" border="1">
            <tr>
                <th>number</th>
                <th>name</th>
                <th>Age</th>
                <th>Gender</th>
            </tr>
        </table>
        <button onclick="req()">Request data</button>
        <img id="img" />
    </body>
    <script>
        function req(){
            document.getElementById("img").src = "img/timg.gif";
            $.ajax({
                url:"http://localhost:8080/MyServer/getData",
                success:function(data){
                    data = JSON.parse(data)
                    console.log(data)
                    for (var i = 0; i < data.length; i++) { 
                        a = data[i];
                        var row = "<tr><td>id</td><td>name</td><td>age</td><td>gender</td></tr>"
                            row = row.replace("id",a.id);
                            row = row.replace("name",a.name);
                            row = row.replace("age",a.age);
                            row = row.replace("gender",a.gender);   
                            document.getElementById("tab").insertAdjacentHTML("beforeend",row);
                    }
                    document.getElementById("img").src = "";    
                },
                error:function(err){
                    console.log(err);
                    document.getElementById("img").src = "";    
                }
            });
        }
    </script>
</html>

A simple case of front and back separation is done

How to maintain the status of user identity?

Posted by konetch on Sun, 22 Dec 2019 10:14:38 -0800