Processing cache _ JSON with json

Source: Internet
Author: User
Processing cache data verification with JSON is the most challenging and changing part of every enterprise Web application. Usually, metadata verification will mix the JavaScript module into the server code. In this article, you will learn how to cache metadata on the client with the help of the server code. The server code will provide string-based metadata in the form of JSON (JavaScript Object Notation. This method also allows Ajax-like processing of multi-value and multi-group attributes.
Every application is developed to solve problems in a certain field. Each field has its own set of rules and specifications that constrain data. When applications apply these constraints to data, the constraints are verified. All applications need to verify the data entered by the user.

Currently, applications generally use a combination of if-else statements to verify data. These statements contain verification data that is hard-coded by the developer or placed through the server code. Generally, developers use server-side code to avoid minor data changes that may lead to the assumerver Page (JSP.

You can use JavaScript Object Notation (JSON) to group and cache metadata, and use JavaScript Functions to access metadata to verify user input.

When JavaScript contains scattered metadata, you cannot control how much data is evaluated and how much data is passed to the client. All server code snippets will be evaluated and sent to the server. However, when using JSON to cache data, you can completely control the amount of metadata sent to the client, because the server code will generate JSON-format metadata. This helps only send metadata to the client corresponding to the user who sees or inputs the data.

You can also use JSON to cache user input data. After the program caches data, it will erase the data field instead of refreshing the screen, which is similar to Ajax. In this way, you can enter another group of data for the same attribute.

Let's explore how to use JSON to cache metadata.

JSON Overview

JSON (JavaScript Object Notation) represents a JavaScript Object in a specific string. If a string with such a form is assigned to any JavaScript variable, the variable then references an object constructed by a string specified to the variable.

For example, assume that a policy object has the following attributes:

Plan Name
Description
Duration
You can use the following JSON string to represent the policy object:

{"Plane": {"Full Life Cover"}, "Description": {"The best life insurance plan"}, "Term": {"20 years "}}

If this string is assigned to any JavaScript variable, the variable accepts data in units of this object. To access data, provide the path of the attribute to be accessed. In this example, assign the preceding string to a variable named policy:

Var policy = {"Plane": {"Full Life Cover"}, "Description": {"The best life insurance plan"}, "Term ": {"20 years "}}

Paste this string into the title section of the HTML page and write the following alarms:

Alert (policy. Plan)

If you view this page in any browser that supports JavaScript, you will see an alert that displays the policy plan.

Example

To demonstrate the JSON performance, let's look at a person object with a vehicle Object List and a person object with one or more vehicles. Each vehicle has the following attributes:

Brand
Registration Code
CC
The browser UI should allow users to add multiple vehicles with excellent application performance (usually inherent ). Each attribute has some associated restrictions or verification rules. You must specify the following rules:

Brand name
The brand name must not contain numbers.
A brand name can contain up to two words, with a space in the middle.
Registration Code
The registration code must all be numbers.
CC
CC must all be numbers.
The minimum value of CC is 50, and the maximum value is 5000.
There will be three input fields that correspond to the vehicle attributes. You can enter information in them. Next, you will see how to group authentication messages to the JSON group and how to access these authentication messages.

Traditional Method

Now, when the vehicle data entered by the user is 40CC, the program must display a message indicating that the input data is not within the valid CC range. You can use the code in Listing 1 to simply display the message:


Listing 1. Traditional code

If (cc <% = minCC %> | cc> <% = maxCC %> ){
Alert (<% = ResourceList. vehicleCCRangeMsg> );
}


ResourceList is a server class that contains international messages about vehicles (such as vehicleCCRangeMsg ). This solution is slightly confusing:


In this method, you add the server code to all client verification functions to check the conditions and display messages.
If you have changed the Organization Methods of metadata and messages (such as server-side classes or variables), it is a headache for you to change the client script verification functions using these metadata and messages.

What does JSON help you do?

How do you feel if you only need to reference a JavaScript variable in the Condition Statement and alarm instead of the server code? You do not need to include the server code in JavaScript. The changes in the stored server metadata and messages do not affect the client script. This method is great, isn't it? Okay, that's what we need to do when using JSON-based metadata cache.

You will use a JavaScript Object to group our verification data and messages to a level. Then access these messages just like accessing a JavaScript object at the access level. You have done that!

When this JSON metadata object is ready, the previous JavaScript code snippet will be similar to listing 2.


Listing 2. Alarm with JSON metadata cache object

If (cc <vehicleValidationsMetadata. CC. minCC |
Cc> vehicleValidationsMetadata. CC. maxCC ){
Alert (vehicleValidationsMetadata. CC. RangeMessage );
}


Now, the question is who will prepare the JSON metadata object? Well, only servers can do this job. The server must generate this JSON object and provide it to the client (browser ). Some Java APIs can help you prepare such JSON objects (in fact any type. See references to view those APIs.

A typical method for generating JSON metadata objects is:

Prepare a hierarchical Java object for the object and its verification message.
ToString () is called for these entities and their verification messages (). These entities and their verification messages are most likely to provide you with a JSON string.
Store the string to another request range.
In JSP, obtain the string and assign it to the braces of the JavaScript variable value.

The final vehicle metadata object looks like listing 3.


Listing 3. Verifying the JSON object of metadata

Var vehicleValidationsMetadata = {
"BrandName ":{
"CanContainDigits": {false },
"MaxWords": {2 },
"FormatMessage": {"Brand Name cannot contain digits ."},
"WordLimitMessage": {"Brand Name cannot contain more than two words "}
}, "RegistrationNumber ":{
"CanContainAlphabets": {false },
"CanContainDigits": {"true "},
"FormatMessage": {"Registration Number can contain only digits ."}
},
"CC ":{
"MinCC": {50 },
"MaxCC": {5000 },
"FormatMessage ":
{"CC can only be numeric "},
"RangeMessage": {"CC can be within range of 50 and 5000 "}
}
}


The server must generate the entire string, except the first and last lines, because the current user language environment may require these messages (and only the server code can do this ). Note that this metadata object is only used to verify vehicles. Ideally, the vehicle metadata object is encapsulated into the person metadata object. In this way, you do not need to create another JavaScript variable, but only need to include this metadata object into the person metadata object.

After preparing the metadata object, you can use the metadata and messages in the object to verify data input and display messages. Now, the JavaScript function for Verifying vehicle input information looks like Listing 4.


Listing 4. Vehicle data verification functions

Function validateVehicleData (){
Var brandName = // get brand name from form field
Var registrationNumber = // get Registration Number from form field.
Var CC = // get CC from form field
Var brandNameTokens = brandName. split ('');
If (brandNameTokens. length> vehicleValidationsMetadata. BrandName. MaxWords ){
Alert (vehicleValidationMessages. BrandName. WordLimitMessage );
}
.
.
.
If ((! VehicleValidationsMetadata. RegistrationNumber. CanContainAlphabets )&&
IsNaN (parseInt (registrationNumber ))){
Alert (vehicleValidationMessages. RegistrationNumber. FormatMessage );
}
Var ccNum = parseInt (CC );
If (ccNum <vehicleValidationMessages. CC. minCC |
CcNum> vehicleValidationMessages. CC. maxCC ){
Alert (vehicleValidationMessages. CC. RangeMessage );
}
}


Does this code look much better? It does not mix server code into JavaScript. If the server changes the method for storing metadata, you do not need to rewrite the client script. This makes the days of JSP programmers easier.

Extended client data cache

Some Web applications require users to enter multiple data for the same property or object. For example, person-vehicle requires personnel to input data for each vehicle they own. If this person owns multiple vehicles, the application must allow the input of data on multiple vehicles. I will reference this type of object as a set of attributes. If multiple groups of attributes contain any attribute that can store multiple data instances, I will call it a multi-value attribute.

At present, the problem between multi-group attributes and multi-value attributes is that data must be input to the same input field. That means you must save the data of the first vehicle before entering the data of the second vehicle. You can solve this problem in two ways:

Send the data of the first vehicle to the server and clear the input fields to allow the user to enter the data of the next vehicle.
Cache the data to the client and clear the input fields to allow the user to enter the data of the next vehicle.
The first method has the problem that the server needs to be accessed every time the data of a vehicle is input. This is not very good; if you have to wait for the server to respond after entering the vehicle data, the user will feel very disappointed. In another method, the response time of the second method is almost zero. Users can quickly enter all vehicle data without waiting. However, you need to consider how to store data on the client. There are more ways to store data on the client:

When you click to add data for the next vehicle, the data is cached to a hidden table field in some form.
Cache data to a JavaScript Object.
If you want to store data in hidden fields, you will be worried about processing many hidden fields or processing hidden field data each time you enter new vehicle data. This is just like string operations that require frequent string processing.

However, the second method for caching data provides an object-oriented method for caching. When you enter new vehicle data, you create a new element in the array object. No clumsy string operations are required. After a user inputs all the vehicle data, you only need to construct a JSON string from the object and send the string to the server by storing it in a hidden field. This method is much better than the first method.

JSON, data cache, and Ajax Functions

When JSON is used to cache data to the client, the system updates the data cache object every time you click Add Vehicle. The JavaScript function used to complete this task may look the same as listing 5.


Listing 5. functions used to add vehicle data to JavaScript objects for Client Cache

Function addVehicleData (){
Var brand = // get vehicle brand; var regNo = // get registration number;
Var cc = // get cc;

VehicleData [vehicleData. length] = new Object ();
VehicleData [vehicleData. length]. brandName = new Object ();
VehicleData [vehicleData. length]. brandName = brand;
// Same way update other two properties
}


Here, vehicleData is the JavaScript variable used for initialization when the user loads the page. It is initialized as a new array object, which is empty or contains vehicle elements of vehicles previously entered by the user.

When this function saves data to a JavaScript object, the program can call another function to clear the input field to allow users to enter new data.

In such applications, users are required to enter multiple groups or multi-value attributes that appear at least or most frequently. You can place these restrictions into JSON metadata objects. In this case, the previous metadata object is changed to the code shown in Listing 6.


Listing 6. JSON metadata objects with a limit on the number of occurrences

Var vehicleValidationsMetadata = {
"MIN_OCC": {0 },
"MAX_OCC": {10 },
"MAX_OCC_MSG ":{"...."},
"MIN_OCC_MSG ":{".....},
// Everything else is the same
}


Then, the addVehicleData () function first verifies the number of occurrences of the data, and then adds the data to the JavaScript Object only when the total number of occurrences does not exceed the allowed limit. Listing 7 shows the check method.


Listing 7. JSON metadata object restriction check

Function addVehicleData (){
If (vehicleData. length == vehicleValidationsMetadata. MAX_OCC-1 ){
Alert (vehicleValidationsMetadata. MAX_OCC_MSG );
} // Everything else is the same
}


The function called when a user submits a page is actually used to verify the minimum number of occurrences. The biggest advantage of this method is that the screen does not need to be refreshed to input new vehicle data. Providing such static screens was once the main goal of Ajax technology, and now you can achieve this goal with JSON. This is about updating JSON Data Objects and processing all the content of the html dom tree through JavaScript. The user response time is the minimum value because all operations are only executed on the client. You can use JSON to provide Ajax functions for applications.

When you click the Save button, the program will call another JavaScript function, which will string this JSON object and store it to the hidden table field submitted by the program to the server. JSON. js (see references) has a JSON. stringify () function that retrieves JavaScript objects as input and returns string output.

The server must be able to understand JSON strings and generate a server object to process and save data. Web site http://www.json.org/java/ I... provides a Java API that handles most of the needs of Java-based applications.

Conclusion

You have seen the powerful use of JSON in this article. The reason is as follows:

JSON provides an excellent object-oriented method to cache metadata on the client.
JSON helps to separate verification data and logic.
JSON helps provide the essence of Ajax for Web applications.
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.