jquery uses AJAX memory overflow problem summary

Source: Internet
Author: User
Tags java reference

Recently do a project, the environment is struts2.3.16,spring3.0,mybatis2.3

When I used jquery's Ajax method to submit a request to return an object, I ran into a memory leak that bothered me for one weeks:

Start calling Ajax methods, the reaction is slow, about 4-5 seconds before the effect will occur.

Repeat several times after the call, the browser crashes directly, the system starts the card, one step at a card ...

Turning on CPU monitoring, when calling the Ajax method, memory flies directly from 56 to 87.

With the MyEclipse backstage burst java.lang.OutOfMemoryError:PermGen space ...

Looking for n long. Run the same results on other people's machines ... Depressed ~ to be delivered immediately, consult a lot of related articles, and finally determine the problem of their own code, not related to the environment, carefully check the code 2 times, did not find any non-compliance with the general problem ....

Suddenly aware of a problem, the project is using the MyBatis framework, and configuring Resultmap in MyBatis can be configured with the associated query: The pass-through data is passed in JOSN format.

One of the issues to be aware of when using JOSN is that you must avoid a composite structure of data dead loops.

For example, Class (Classes), students (Student) two classes, on the Classes side has the List<student> students attribute, and Student Classes properties,

They have direct references to each other, and when you use JOSN to pass data, there is a dead loop of infinite-level queries. The JOSN data that is passed is also unusually large ...

For my project, since the use of STRUTS2 as the controller, so when using jquery to invoke Ajax, I was directly through the STRUTS2 integrated josn (lazy), the code is as follows:

Ajax, a dynamic cascading request method:

$ (' #companySelect '). Change (function(){      vardeptid=$ ( This). Val (); varsenddata={' DeptID ':d Eptid};//Data josn Format Data      varUrl= "User!searsecondselect";//Address$.ajax ({//the notation is in JOSN format.Url:url,//AddressData:senddata,//ParametersType: ' Post ',//Set the submission typeSuccessfunction(data) {//callback function for successful request              varValue= ' <option value= "0" >--Please select Department--</option> ';  for(vari=0;i<data.deptlist.length;i++) {Value+ = ' <option value= ' ' +data.deptlist[i].deptid+ ' > ' +data.deptlist[i].deptname+ ' </option> '              }              $(' #deptIdSelect '). HTML (value); }      });});

Request method Code: By querying the database, put the results into the appropriate encapsulated properties (deptlist).

 Public String Searsecondselect () {       this. Setdeptlist (Ds.selectall (DeptID));        return "Searchtwodept";}

Struts.xml configuration: Passing JOSN data by inheriting the Json-default package

< Packagename= "Zhanglu"namespace="/"extends= "Json-default">        <Actionname= "User"class= "Useraction">            <resultname= "Success">/permission/user_manage.jsp</result>            <resultname= "Exits">/permission/exits.jsp</result>            <resultname= "PostInfo"type= "JSON"></result>            <resultname= "Searchtwodept"type= "JSON"></result>        </Action></ Package>

The entire AJAX request to the callback function, without any problems, runs everything OK.

However, in another Ajax method memory overflow, I need to query an employee information object (employee) returned on the page display, tried a lot of methods, and finally decided to change a josn delivery method, do not use the Struts2 Json-default way, the other is as follows:

Ajax methods. Request a method that queries Empinfo information, where Empannexinfos references an object for another class

var senddata = { ' UserName ': UserName};//Data josn Format Datavar url = "User!searchempinfo";//Address$.ajax ({//Note that the JOSN format is recommended for use in Ajax because the speed is fastUrl:url,//AddressData:senddata,//ParametersType: ' Post ',//Set the submission typeSuccess:function (data) {//callback function for successful requestvar emps=eval (data); $ (Emps). Each (function (i, EMP) {var Empann=eval (Emp.empannexinfos); $ (Empann). Each (function (i, EMA) {var img= ' ; $(' #empInfo. Images '). HTML (IMG);             }); var empinfo= ' Name: ' +emp.empname+ ' emp.empsalary; Empinfo+ = ' Emp.emtime; $(' #empInfo. Einfo '). HTML (empinfo);       }); }
});

Action method:

 Public voidSearchempinfo ()throwsexception{String name= This. GetUserName (). Trim ();  This. Setempinfo (Emd.getempinfobyempnum (name)); if(Empinfo.getempannexinfos () = =NULL) {System.out.println ("Annexinfo is null"); } PrintWriter out= This. GetResponse (). Getwriter (); Jsonconfig CFG=Newjsonconfig ();Jsonarray jsonlist=Jsonarray.fromobject (EMPINFO,CFG);
System.out.println (Jsonlist.tostring ());//output JOSN Data string Out.print (Jsonlist.tostring ()); }

If you use PrintWriter, you do not need to configure Struts.xml

The result of the final run is still a memory overflow, and when I see the josn string of the console output copied to Sublimetext, there is a scary result:

Dense n long piece, look carefully, these chaotic data, is josn. I think this is the real reason for memory overflow, although the employee object itself is not large, but in Employeeinfo.java reference to the other 7 entity class references, 7 entity classes also refer to the EmployeeInfo object, this tangled up ... There is no doubt that direct delivery of employee object josn into a dead loop is the root cause of memory overflow ...

Search the web for ways to get rid of josn:

Reference: Methods of http://www.2cto.com/kf/201303/198961.html

Modify the action method above:

 Public voidSearchempinfo ()throwsexception{String name= This. GetUserName (). Trim ();  This. Setempinfo (Emd.getempinfobyempnum (name)); if(Empinfo.getempannexinfos () = =NULL) {System.out.println ("Annexinfo is null"); } PrintWriter out= This. GetResponse (). Getwriter (); Jsonconfig CFG=NewJsonconfig (); Cfg.setexcludes (Newstring[]{"EmployeeInfo", "borders", "Workovertimes", "Askforleaveeaas", "Compacts", "goonerrandses", "Empboons", " Udops "," replacingposts "," Transferemps "," rewardpunishments "," Timebooks "," POST "}); Jsonarray jsonlist=Jsonarray.fromobject (EMPINFO,CFG);

System.out.println (Jsonlist.tostring ());//output JOSN data string
        
}

This time to view the JOSN string, filtering succeeds:

Page Run Effect:

Memory overflow finally solved .....

It's time to have a good sleep ....

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.