The complete process of ajax parsing from the front end to the back end in jquery, jqueryajax

Source: Internet
Author: User

The complete process of ajax parsing from the front end to the back end in jquery, jqueryajax

Principles:

1. When you use get to access the browser, the following parameters are often used:

The GET access to the browser is idempotent, that is, the same URL has only one result [the same means that the entire URL string matches completely], so if the URL string does not change during the second visit, the browser directly shows the result of the first visit. POST is regarded as a variable access (the browser believes that the submission of POST must be changed) to prevent the idempotent access of GET from being added to the URL? + New Date (); [In short, the URL string for each access is different]. This principle should also be followed when designing web pages.

2. Differences between get and post in ajax:

Get method:
The get method can be used to transmit simple data, but the size is generally limited to 1 kb, and the data is appended to the url for sending (http header transfer), that is, the browser attaches the form field elements and their data to the resource path in the request line according to the URL parameter format. The most important thing is that it will be cached by the client's browser, so that others can read the customer's data from the browser's historical records, for example, account and password. Therefore, in some cases, the get method may cause serious security problems. In short, the GET method delivers a small amount of data, high processing efficiency, low security, and will be cached, whereas the POST method does not.

Post method:
When the POST method is used, the browser sends the form field elements and their data to the Web server as the entity content of the HTTP message, rather than as the URL address parameter, the amount of data transmitted in POST mode is much larger than that transmitted in GET mode.

Next, let's look at our front-end in the Code:

We can see that the front-end code includes:

When the background receives the front-end $. when the path in ajax () is (url: "/report/loadAssetsTransactionsByRegionTime. the Interceptor is configured in xml, which is completed by 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, it is the configuration file of the struts2 core controller code in web. xml. The ing path is generally mapped to "/*". Let's take a look at the specific interception actions below.

<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 Action and interceptor. The action of struts2 must be defined under a specified package space. The package element in the struts. xml file is used to define the package configuration. The struts2 framework has two core configuration files. The struts. xml file is mainly used to manage the Action ing in the application and the mappings between the Action processing results and physical resources. In addition, the Struts2 framework also contains a struts. properties file, which provides a large number of constant attributes of the Struts2 framework. However, we recommend that you configure these constant attributes in the struts. xml file.

<! -- Define the Action whose processing request URL is dailyMonitoringAction --> <action name = "loadAssetsTransactionsByRegionTime" class = "dailyMonitoringAction" method = "loadAssetsTransactionsByRegionTime"> <! -- Defines the ing between the processing result string and the resource. The type returned by this action is json --> <result name = "success" type = "json"> <! -- Specify the json returned field --> <param name = "includeProperties"> * </param> </result> </action>

Then let's look at the Action. SpringMVC can be used to transmit parameters, or struts2 can be used to transmit parameters. The following is the SpringMVC method to transmit data.

@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 Use http: // 127.0.0.1: 8080/demo/index. jsp? Name = aty & age = 20 as an example. There are two ways to obtain the request parameter value in struts2 action: first, define the variable with the same name in action and provide 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, you can manually obtain 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 are the differences between the two methods? Obviously, it is the difference between a member variable and a local variable. We know that an action can define multiple public methods to process different foreground requests. If the same request parameter is used by multiple methods, the first method is suitable. If a request parameter is used by only one method, the second method is suitable. The principle is to ensure that the same parameter name appears only once in the action Code (avoid repetition), and the variable scope should be as small as possible (Code cohesion ). To encapsulate http Request Parameters to object classes, see the struts2 model driver http://blog.csdn.net/li_tengfei/article/details/6098145. The following describes how to encapsulate parameters in 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 parameters in 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 parameters into 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);

We can see that using Map to receive http request parameters is no different from using the entity class, and the methods in js and java are the same.

 

Add several knowledge points:

1. springMVC and struts2 comparison (reference: http://blog.csdn.net/gstormspire/article/details/8239182)

We used the traditional configuration file method in struts2, and did not use the legendaryZero Configuration. Spring3 mvc can be considered to have 100% Zero Configuration (except for configuring spring mvc-servlet.xml ).

First, mechanism: the entry of spring mvc is servlet, while struts2 is filter (it should be pointed out that the filter and servlet are different. I used to think that filter is a special type of servlet), which leads to different mechanisms between the two. The difference between servlet and filter is involved here.

Second, performance: spring is slightly faster than struts. Spring mvc is a method-based design, while sturts is a class-based design. Each request is sent with an action instance, and each action is injected with attributes. spring is based on methods with finer granularity, but be careful with the data as controlled in servlet. Spring3 mvc is a method-level interception. After the method is intercepted, the request data is injected according to the Annotation on the parameter. In spring3 mvc, a method corresponds to a request context. The struts2 framework is a Class-level interception. Every time a request is sent, an Action is created, and the setter getter method is called to inject the data in the request;Struts2 actually deals with requests through the setter getter method;In struts2, an Action object corresponds to a request context.

Third, parameter passing: struts can accept parameters using attributes when accepting parameters. This means that parameters are shared by multiple methods.

Fourth, design ideology: struts is more in line with oop programming ideas, so spring is more cautious and can be expanded on servlet.

Fifth, spring mvc is method-level interception. A method corresponds to a request context, and the method corresponds to a url at the same time. Therefore, spring3 mvc can easily implement restful URLs in the architecture itself. Struts2 is a Class-level interception. A Class corresponds to a request context. It is difficult to implement a restful url, because a method of struts2 action can correspond to a url, while its class attributes are shared by all methods, in this way, the method to which the object belongs cannot be identified using annotations or other methods. Spring3 mvc methods are basically independent, with exclusive request response data. The request data is obtained through parameters, and the processing results are returned to framework methods through ModelMap without sharing variables, struts2 is messy. Although the methods are independent, all their Action variables are shared, which does not affect the program running, but it gives us coding and troubles when reading the program.

Therefore, it is summarized as follows: "struts2 is a Class-level interception. A Class corresponds to a request context. springmvc is a method-level interception. A method corresponds to a request context, the method corresponds to a url at the same time, So spring3 mvc can easily implement restful url in terms of architecture itself. The implementation of struts2 architecture is difficult, because a method of struts2 action can correspond to a url. The class attributes are shared by all methods, so they cannot be identified by annotations or other methods. Spring3mvc methods are basically independent, with exclusive request response data. The request data is obtained through parameters, and the processing results are returned to the framework through ModelMap. Methods do not share variables, while struts2 is messy. Although methods are independent, all their Action variables are shared. This will not affect the program running, but it will cause us trouble when coding and reading the program. Struts2 needs to encapsulate each Request. It encapsulates the Request, Session, and other Servlet lifecycle variables into one Map for each Action and ensures thread safety. Therefore, in principle, it is relatively memory-consuming.

2. Use of JSTL in projects: JSTL (JSP Standard Tag Library, JSP Standard Tag Library) is a well-developed open-source JSP Tag Library.

3. Use of the Map interface in java: the map interface is combined according to the key-value pairs of <key, value>. The key is an index and an object, which is different from the array. When using 1, 2, 3, 4... (the index of an array can only be a subscript), we generally select a subclass of the Map interface instead of using the Map interface directly. (The Collection container contains the Set and List interfaces. The Set contains HashSet, which includes the sorted List and ArrayList. The separate Map interface only contains HashMap ).

  JavaSome of the most common classes in. The most common collection classes are List and interface Map. The specific implementation of List includes ArrayList and Vector, which are variable-size lists and are suitable for building, storing, and operating the List of elements of any type of object. List is applicable to accessing elements by Numerical index, where the data is ordered and can be repeated. The data in the Set is unordered and cannot be duplicated.

First, let's look at the overwrite implementation of the two methods in our Object class in the Map interface: equals (obj) method, used to compare the equivalence between the specified Object and the Map; hascode () method, returns the hash of this Map. (So the question is, what is the use of the hashcode () method in java? The hascode () method is used to compare whether two objects are equal. When the hascode () values of two objects are not equal, the two objects are certainly not equal. If the hascode () of the two objects () the methods are equal, and the equals () method is further compared. Because the value of hascode () is int, It is faster to compare them, so the efficiency of comparison can be improved.);

  Each java object has a unique identifier. The hash method in the object class directly returns the internal ID of the object, which is different from the string hash method, the object hash method can be used to distinguish different objects. because the original object does not have any meaningful value, it can be used to calculate the hash. The unique id fully reflects the object-oriented programming philosophy.

4. Several recommendation blogs:

Introduction (Role of hascode)Http://www.cnblogs.com/dolphin0520/p/3681042.html

Conclusion: 1. The hashCode method is used to reduce the number of calls to the equals method and improve program efficiency.

2. When designing a class, you need to override the equals method, such as the String class. But be sure to rewrite the hashCode method while rewriting the equals method.

Introduced the string similarity algorithm (applicable to DNA comparison and web page clustering)Http://www.cnblogs.com/huangxincheng/archive/2012/11/11/2765633.html

Classic KMP AlgorithmHttp://www.ruanyifeng.com/blog/2013/05/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm.html

Conclusion: 1. http://www.ruanyifeng.com/blog/algorithm/ this is the author's post on mathematics and algorithms.

 

 

  

 

  

  

 

 

 


 

 

 

 

 

 

 

 

 

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.