Processing caching with JSON _json

Source: Internet
Author: User
Tags prepare require
Data validation is the most challenging and ever-changing part of every enterprise Web application. Typically validating metadata causes the JavaScript module to be mixed with server-side code. In this article, you will learn how to cache metadata in the client's best way with the help of server code, which will provide string metadata in the form of JSON (JavaScript Object notation). This approach also allows for multiple-valued and multiple-group properties to be handled in an Ajax-like manner.
Each application is developed to address an area of problem. Each domain has its own set of rules and specifications for constraining data. When an application applies these constraints to data, the constraint is validated. All applications need to validate the data entered by the user.

Currently, applications typically use a combination of IF-ELSE statements to validate data. These statements contain validation data that the developer has hard-coded or placed through server-side code. Typically, developers use server-side code to avoid subtle data changes that could result in JavaServer Page (JSP).

You can use JavaScript Object notation (JSON) to group and cache metadata, and to use JavaScript functions to access metadata to validate user input.

When there are scattered metadata in JavaScript, you cannot control how much data the server evaluates and how much data is passed to the client. All server-side code fragments are evaluated and sent to the server. However, when you use JSON to cache data, you have full control over the amount of metadata sent to the client, because the server-side code generates metadata in JSON form. This helps to send metadata only to clients that correspond to the users who see or enter data.

You can also use JSON to cache data entered by a user. After the program caches the data, it erases the data field instead of refreshing the screen, similar to Ajax. In this way, a user can enter another set of data for the same property.

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

JSON Overview

Using JSON (that is, JavaScript Object notation), JavaScript objects are represented in a specific string form. If you assign a string with such a form to any JavaScript variable, the variable then references an object that is built by the string that is assigned to the variable.

For example, suppose you have a policy object that has the following properties:

Plan Name
Describe
Duration
You can use this JSON-form string to represent the policy object:

{"Plane": {"Cover"}, "Description": {"The Best Life Insurance Plan"}, "Term": {"Years"}}

If you assign this string to any one of the JavaScript variables, the variable will accept the data in this object unit. To access data, provide the path to the property that you want to access. For this example, assign the above string to a variable named policy:

var policy = {"Plane": {"Full Life Cover"}, "Description": {"The Best Life Insurance Plan"}, "Term": {"Years"}}

Paste the string into the title section of the HTML page, and then write the following alert:

Alert (policy. Plan)

If you view this page in any JavaScript-enabled browser, you will see an alert showing the policy plan.

Example

To demonstrate the performance of JSON, let's look at a person object with a list of vehicle objects and a person object that can own one or more vehicles. Each vehicle has the following properties:

Brand
Registration code
Cc
The browser UI should allow users to add multiple vehicles with excellent application performance (usually inherent requirements). Each property has some restrictions or validation rules associated with it. You need to specify the following rules:

Brand name
Brand names must not contain numbers.
The brand name can contain up to two words, with a space in between.
Registration code
The registration code must be all numbers.
Cc
CC must be all numbers.
The minimum value for CC is 50, and the maximum value is 5000.
There will be three input fields corresponding to the vehicle properties, in which the user can enter information. Next, you'll see how to group the validation messages into the JSON group and how to access the validation messages.

Traditional methods

Now, when the user enters a vehicle data of 40CC, the program must display a message stating that the data entered is not in a valid CC range. You can use the code in Listing 1 to simply display this message:


Listing 1. Traditional code

if (cc < <%= MINCC%> | | cc > <%= maxcc%>) {
Alert (<%= resourcelist.vehicleccrangemsg >);
}


Resourcelist is a server-side class that contains internationalized messages about vehicles (such as vehicleccrangemsg). This approach solves the problem with a bit of confusion:


In this approach, you will add server-side code to all client validation functions to check for conditions and display messages.
If you change the organization method of metadata and messages, such as server-side classes or variables, you will have a headache for changing the client script validation functions that use these metadata and messages.

What can JSON do to help you?

How would you feel if you simply referred to a JavaScript variable instead of a server-side code in a conditional statement and alert? There is no need to include server-side code in JavaScript, and changes in saved server-side metadata and messages do not affect client script. This is a great way, isn't it? Well, that's what you do when you cache metadata based on JSON.

You will use a JavaScript object to group our validation data and messages into one hierarchy. The message is then accessed like a JavaScript object at the access level. That's it, you've done it!

When this JSON metadata object is ready, the previous JavaScript snippet will resemble listing 2.


Listing 2. Alerts with JSON metadata cache objects

if (cc < VehicleValidationsMetadata.CC.minCC | |
CC > VehicleValidationsMetadata.CC.maxCC) {
alert (vehicleValidationsMetadata.CC.RangeMessage);
}


Now, the question is who is going to prepare the JSON metadata object? Well, only the server can do the work. The server must generate this JSON object and provide it to the client (browser). Some Java APIs can help you prepare this class (in fact, any kind of) JSON object. See resources to see those APIs.

Typical ways to generate a JSON metadata object are:

Prepares a level Java object for the entity and its validation messages.
Call ToString () on these entities and their validation messages. These entities and their validation messages are most likely to provide you with a JSON-form string.
Save the string to a request scope.
In the JSP, get the string and assign it to the curly braces of the JavaScript variable value.

The final vehicle Meta data object looks like Listing 3.


Listing 3. Validating metadata JSON objects

var vehiclevalidationsmetadata = {
"Brandname": {
' Cancontaindigits ': {false},
' Maxwords ': {2},
"FormatMessage": {"Brand Name cannot contain digits."},
"Wordlimitmessage": {"Brand Name cannot contain more than two"}
}, "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 and 5000"}
}
}


The server must generate the entire string, except for the first and last lines, because the current user locale may require these messages (and only server-side code can do this). One thing to be aware of here is that this metadata object is used only for validating vehicles. Ideally, the vehicle metadata object is encapsulated into the person metadata object. That way, you don't need to create another JavaScript variable, just include the metadata object in the person metadata object.

When this metadata object is ready, you can use the metadata and messages in that object to validate data entry and display messages. Now, the JavaScript function that validates the vehicle's input looks like listing 4.


Listing 4. Vehicle Data validation function

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 with server code in JavaScript. If the server side changes the method that stores the metadata, you do not need to rewrite the client script again. This makes life easier for JSP programmers.

Extended Client Data caching

Some WEB applications require users to enter multiple data for the same property or object. For example, person-vehicle requires that people enter data for each vehicle they own. If the person owns more than one vehicle, the application must be allowed to enter data for multiple vehicles. I'm going to refer to this object as a set of multiple properties. If multiple sets of properties contain any properties that can hold multiple instances of data, I will call them multivalued attributes.

The problem with multiple-group and multivalued properties is that you must enter data into the same input field. That means you must first save the data for the first vehicle you entered before entering the data for the second vehicle. There are two ways you can work around this problem:

Send data from the first vehicle to the server and empty the input fields to allow the user to enter data for the next vehicle.
The data is cached on the client and the input fields are emptied to allow the user to enter data for the next vehicle.
The problem with the first approach is that every time a vehicle is entered, the data needs to be accessed once to the server. This is not good; users will be disappointed if they have to wait for the server to respond after entering the vehicle data. In other ways, the second method has almost zero response time. Users can quickly enter all vehicle data without waiting. But what you need to consider here is how to store the data on the client. There are more ways to store data on a client computer:

The data is cached in some form to a hidden table field when the user clicks to add data for the next vehicle.
Caches data into a JavaScript object.
If you want to store data in a hidden field, you will be bothered to handle many hidden fields or work with hidden field data each time a user enters new vehicle data. This is like having string operations that require frequent processing of strings.

But the second method of caching data provides an object-oriented approach to caching. When the user enters the new vehicle data, you create a new element in the array object. No clumsy string manipulation is required. Once the user has finished losing all the vehicle data, you simply build 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 caching, and Ajax features

When you use JSON to cache data to a client, the system updates the data cache object each time the user clicks the Add Vehicle button. The JavaScript function used to complete this task may look like listing 5.


Listing 5. Functions for adding vehicle data to a JavaScript object for client caching

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 that is used to initialize when a user loads a page. It is initialized to a new array object that is empty or contains the vehicle elements of the vehicle that the user previously entered.

When this function saves data to a JavaScript object, the program can call another function to empty the input fields to allow the user to enter new data.

In such applications, users are required to enter multiple or multi-valued attributes with the least number of occurrences or occurrences. You can place these restrictions into the JSON metadata object. In this case, the previous metadata object becomes the code shown in Listing 6.


Listing 6. JSON metadata object with a limit of occurrences

var vehiclevalidationsmetadata = {
' Min_occ ': {0},
' Max_occ ': {10},
"Max_occ_msg": {"..."},
"Min_occ_msg": {"...},
Everything else is the same
}


The Addvehicledata () function then validates the number of occurrences of the data and then adds the data to the JavaScript object only if the total number of occurrences does not exceed the allowable 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 approach is that the screen does not need to be refreshed to enter new vehicle data. Providing such static screens was once the primary goal of Ajax technology, and you can now accomplish this with JSON. This is all about updating the JSON data object and processing the HTML DOM tree through JavaScript. The user response time is minimal because all operations are performed only on the client. You can use JSON to provide AJAX functionality to your application.

When the user clicks the Save button, the program invokes another JavaScript function that will string the JSON object and store it in a hidden table field that the program submits to the server. Json.js (see Resources) has a json.stringify () function that takes the JavaScript object as input and returns the string output.

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

Conclusion

You see the powerful uses of JSON in this article. Boils down to the following:

JSON provides an excellent object-oriented approach to caching metadata to clients.
JSON helps isolate the validation data and logic.
JSON helps provide the essence of Ajax for WEB applications.

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.