Comprehensive analysis of ajax process from front-end to back-end in jquery

Source: Internet
Author: User
Tags hash json object object prepare unique id

1.get Way to access the browser, often add parameter reasons:

Get access Browser is idempotent, is a same URL only one result [the same refers to the entire URL string exactly match], so the second visit if the URL string does not change, the browser is directly come up with the results of the first visit. Post is considered to be a variable access (the browser thinks that the Post's submission must be changed) to prevent the idempotent access of get from being appended to the URL. +new Date (); [In short, make each access URL string different]. You should also adhere to this principle when designing Web pages.

The difference between get and post in the 2.ajax mode:

Get Way:
You can transfer simple data in Get mode, but the size is typically limited to 1KB, the data is appended to the URL (HTTP header transfer), that is, the browser appends individual form field elements and their data to the resource path in the request line in the format of the URL parameter. The most important point is that it is cached by the client's browser, so that other people can read the customer's data, such as account number and password, from the browser's history. Therefore, in some cases, the Get method poses a serious security problem. In short, get-mode transfer data is small, high processing efficiency, low security, will be cached, and post instead.

Post method:
When using post, the browser sends individual form field elements and their data to the Web server as the entity content of the HTTP message, rather than as a parameter to the URL address, and the amount of data that is passed by post is much larger than the amount of data that is transmitted using the GET method.

Next, look at our front desk in the code:

We have seen the code in the foreground:

When the path in the front-end $.ajax () is received in the background (URL: "/report/loadassetstransactionsbyregiontime"), We've configured interceptors in Web.xml, part of the STRUTS2 core controller: Strutsprepareandexecutefilter, which includes two parts strutspreparefilter and Strutsexecutefilter.


<filter>
<filter-name>struts-prepare</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareFilter</filter-class>
</filter>
<filter>
<filter-name>struts</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsExecuteFilter</filter-class>
</filter>



As shown above, is the STRUTS2 core controller code in the Web.xml configuration file, mapping path is generally mapped to "/*", and then see the following specific interception action


<filter-mapping>
<filter-name>struts-prepare</filter-name>
<url-pattern>/main/*</url-pattern>
<url-pattern>/inspection/*</url-pattern>
<url-pattern>/report/*</url-pattern>
<url-pattern>/audit/*</url-pattern>
<url-pattern>/ajax/*</url-pattern>
<url-pattern>/location/*</url-pattern>
<url-pattern>/admin/*</url-pattern>
<url-pattern>/calculation/*</url-pattern>
<url-pattern>/conf/*</url-pattern>
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
</filter-mapping>
<filter-mapping>
<filter-name>struts</filter-name>
<url-pattern>/main/*</url-pattern>
<url-pattern>/inspection/*</url-pattern>
<url-pattern>/report/*</url-pattern>
<url-pattern>/audit/*</url-pattern>
<url-pattern>/ajax/*</url-pattern>
<url-pattern>/location/*</url-pattern>
<url-pattern>/admin/*</url-pattern>
<url-pattern>/calculation/*</url-pattern>
<url-pattern>/conf/*</url-pattern>
<dispatcher>FORWARD</dispatcher>
</filter-mapping>



The core of struts is the action and interceptor, and the STRUTS2 action must be defined in a specified packet space. The package element in the Struts.xml file defines the package configuration. The STRUTS2 framework has two core profiles, where struts.xml files are primarily responsible for managing action mappings in applications and mapping relationships between action processing results and physical resources. In addition, the STRUTS2 framework contains a struts.properties file that Struts2 a large number of constant properties of the framework. However, it is often recommended that you configure these constant properties in the Struts.xml file.


<!--define action--> that handles request URLs as Dailymonitoringaction
<action name= "Loadassetstransactionsbyregiontime" class= "Dailymonitoringaction" Loadassetstransactionsbyregiontime ">
<!--define the mapping relationship between the processing result string and the resource, which specifies that the returned type is json-->
<result name= "Success" type= "JSON" >
<!--Specify the domain--> the JSON returns
<param name= "Includeproperties" >*</param>
</result>
</action>



Then we look at the action, you can pass the parameter in SPRINGMVC way, or you can pass the parameter by using the Struts2 method, the following is the way to pass the data using the SPRINGMVC.


@RequestMapping (value= "/loadassetstransactionsbyregiontime", Method=requestmethod.get)
public string Loadassetstransactionsbyregiontime (string starttime, String endtime, httpservletresponse response) {
String starttime = StartTime;
String endtime = Endtime;
LINEVM = new LINECHARTVM ();
Linevm.settitle ("Assets Transactions by Region");
Linevm.setyaxisname ("Transactions");
Map<string, map<string, double>> assetregionmap = Dailymonitoringservice
. Loadassetregiontransactiontime (StartTime, Endtime);
Linevm.setcategories (New arraylist<string> (Assetregionmap.keyset ()));
map<string, list<double>> seriesmap = Pivotingmap (Assetregionmap, 0D);
list<chartserievm> serieslist = new arraylist<chartserievm> ();
For (String Key:seriesMap.keySet ()) {
CHARTSERIEVM CHARTSERIEVM = new CHARTSERIEVM ();
Chartserievm.setname (key);
Chartserievm.setdata (Seriesmap.get (key));
Serieslist.add (CHARTSERIEVM);
}
Linevm.setseries (serieslist);
return SUCCESS;
}



Alternatively, we can use STRUTS2 to solve this problem, we take the http://127.0.0.1:8080/demo/index.jsp?name=aty&age=20 as an example, struts2 action to get the request parameter value, In general there are 2 ways: The first defines a variable with the same name in the action, providing the Get/set method


public class Demoaction
{
private String name;
private int age;

Public String GetName ()
{
return this.name;
}

public void SetName (String name)
{
THIS.name = name;
}

public int Getage ()
{
return this.age;
}

public void SetName (int age)
{
This.age = age;
}
}





Alternatively, use the manual fetch HttpServletRequest and then call Request.getparameter ()


public class Demoaction
{
Public String Execute ()
{
HttpServletRequest request = Servletactioncontext.getrequest ();
String name = Request.getparameter ("name");
String age = request.getparameter (' age ');
}
}



What is the difference between these 2 ways? is obviously the difference between a member variable and a local variable. We know that an action can define multiple public methods to handle different foreground requests. If the same request parameter is used by more than one method, it is appropriate to use the first method, and if a request parameter is only used by one way, it is appropriate to use the second way. The principle is to ensure that the same parameter name appears only once in the action code (avoid repetition), and that the scope of the variable is as small as possible (the code gathers). The way to encapsulate HTTP request parameters into entity classes is to refer to the STRUTS2 model-driven http://blog.csdn.net/li_tengfei/article/details/6098145. Let's look at how to encapsulate the parameters in the map and list.


public class Demoaction
{
Private map<string,string> Requestmap = new hashmap<string,string> ();

Private list<user> requestlist = new arraylist<user> ();

}</user></user></string,string></string,string>



JS encapsulates the parameters into the list


var params = {};
params["Requestlist[0].id"] = $ ("#person_id"). attr ("value");
params["requestlist[0].username"] = "aty";
params["Requestlist[0].password"] = "123";
params["requestlist[0].age"] = 25;
params["requestlist[0].address"] = "";

$.post (Url,params);



JS encapsulates the parameters to the map


var params = {};
params["Requestmap.id"] = $ ("#person_id"). attr ("value");
params["requestmap.username"] = "aty";
params["Requestmap.password"] = "123";
params["requestmap.age"] = 25;
params["requestmap.address"] = "";

$.post (Url,params);



You can see that using a map to receive HTTP request parameters is no different from using the entity classes, and the same is the practice in both JS and Java.



Add a few points of knowledge:

1, Springmvc and struts2 contrast (refer to: http://blog.csdn.net/gstormspire/article/details/8239182)

We adopted the traditional configuration file in Struts2, and did not use the legendary 0 configuration. SPRING3 MVC can be considered to have been configured for 100% 0 (in addition to configuring spring Mvc-servlet.xml).

First, the mechanism: Spring MVC's entrance is a servlet, and Struts2 is the filter (here to point out that the filter and servlet are different.) It used to be that the filter is a special kind of servlet, which leads to a different mechanism, which involves the difference between a servlet and a filter.

Second, performance: Spring will be slightly faster than struts. Spring MVC is a method based design, and Sturts is based on a class, each time a request takes an instance of an action, each action is injected with attributes, and spring is based on the method, the granularity is finer, but be careful to control the data just like in the servlet. SPRING3 MVC is a method-level intercept that, when intercepted to a method, injects the request data into an annotation based on the parameters, and in Spring3 MVC, a method corresponds to a request context. The STRUTS2 framework is class-level interception, creates an action every time a request is made, and then invokes the setter getter method to inject the data in the request; Struts2 is actually dealing with the request through the setter getter method. ; struts2, an Action object corresponds to a request context.

Third, the parameter passes: Struts is when accepts the parameter, may use the attribute to accept the parameter, this explained that the parameter is lets several methods share.

The design idea: struts is more consistent with OOP programming ideas, and spring is more cautious and expands on the servlet.

V, Spring MVC is a method-level interception, a method that corresponds to a request context, and a method that corresponds to a URL, so it is easy to implement restful URLs from the architecture itself spring3 MVC. STRUTS2 is class-level interception, a class corresponds to a request context, and it is difficult to implement restful URLs because a method of the Struts2 action can correspond to a URL, and its class attributes are shared by all methods. It is also impossible to identify the method by annotation or other means. Spring3 MVC method is basically independent of the request response data, requests data through parameters, processing results through Modelmap to the framework method to return to not share the variable, and struts2 is more chaotic, although the method is independent, But all of its action variables are shared, which does not affect the program running, but it gives us the code to read the program and cause trouble.

Therefore, the summary is as follows: "Struts2 is class-level interception, a class corresponds to a request context, SPRINGMVC is a method-level interception, a method corresponds to a request context, and the method also corresponds to a URL, so to speak from the architecture itself SPRING3 MVC is easy to implement restful URLs. The STRUTS2 architecture is hard to implement because a method of struts2 action can correspond to a URL. While its class attributes are shared by all methods, it is not possible to identify the method by annotation or otherwise. The Spring3mvc method is basically independent of the request response data, requests the data through the parameter obtains, the processing result passes through the modelmap to the frame. Methods do not share variables, and struts2 is messy, although the method is independent, but all of its action variables are shared. This does not affect the program running, but it gives us trouble encoding the program to read. Because STRUTS2 needs to encapsulate each request, encapsulate the variables of the servlet lifecycle, such as Request,session, into a single map that is used by each action and ensures thread safety. So in principle, it's more memory-intensive.

2, JSTL in the project use: JSTL (JSP Standard tag library,jsp standard tag library), is a continuous improvement of the open source code JSP tag Library.

3, the use of the map interface in Java: Map interface in accordance with the <key,value> of the value of the other side of the combination, key is an index, itself is an object, this is different from the array. 1,2,3,4 ... (The index of an array can only be subscript) when used, the general selection is a subclass of the map interface, rather than using the map interface directly. (The collection container contains the set and list interfaces, and the set contains the LinkedList and ArrayList in the Hashset,list, and only hashmap in a separate map interface).

Some of the most commonly used classes in Java. The most commonly used collection classes are the list and interface map. The specific implementations of list include ArrayList and vectors, which are variable sized lists that are more suitable for building, storing, and manipulating the list of elements of any type of object. The List applies to the case where the element is accessed by a numeric index, where the data is sequential and repeatable. The data in the set is not sequential and cannot be duplicated.

First look at the two methods in our object class that are overridden in the map interface: the Equals (obj) method, which compares the equivalence between the specified object and the map; Hascode () method returns the hash of this map. (So the question is, what's the use of the Hashcode () method in Java?) Use the Hascode () method to compare two objects for equality, and when two objects have Hascode () values that are not equal, two objects are definitely not equal, and if the Hascode () method of two objects is equal, the Equals () method is further compared because of the Hascode () The values are int, comparing them faster, so you can increase the efficiency of the comparison;

Each Java object has a unique identity, and the hash method in the object class is directly returning the internal ID number of the object, which is different from the hash method of string. The hash method of object can be used to distinguish between different objects. Because the original object object does not have any meaningful value to compute the hash. The unique ID fully reflects the object-oriented programming idea.

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.