A Cause of StackOverflowError and its solution
An error code
Stacktraces
org.apache.jasper.JasperException: javax.servlet.ServletException: java.lang.StackOverflowError
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:505)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:417)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:320)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:266)
javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
Omit the remainder
JsonConfigUtil removes dead loop tool class download address struts2+Hibernate+Spring project
Cause analysis,
StackOverflowError is the meaning of stack overflow
. When I encountered this problem myself, almost all the reasons I found were caused by recursion or endless loop. My own project was caused by writing the toString method in the entity class. A concrete analysis
// One of the entity classes
public class Hobby implements java.io.Serializable {
// Fields
private Integer hobbyId;
private String hobbyName;
private Set<Nurse> nurses = new HashSet<Nurse>();
}
// Another one of the entity classes
public class Nurse implements java.io.Serializable {
// Fields
private Integer id;
private Dept dept;
private String name;
private Integer age;
private String content;
private String datea;
private Set<Hobby> hobbies = new HashSet<Hobby>();
}
It can be seen that each entity class has a set set of the other. If tostring method is used to output Hobby of one of the entity classes, its corresponding set
collection will also output, so will another entity class in it, and then there is also Hobby set collection in Nurse. So you’re stuck in an infinite loop of infinite output
One of the solutions
Delete the toString method in the entity class, and an error will be reported.
@Override
public String toString() {
return "omit";
}
Solution number two
Set the set collection to null
, Nurse Nurse = new Nurse(); set the set collection to null
, Nurse Nurse = new Nurse();
nurse.setNurses(null);
Solution 3 (also the most commonly used)
Use JsonConfigUtil to remove the dead-loop tool class
JsonConfig config = JsonConfigUtil.getConfig();
JSONArray.fromObject(list, config);
Put the object or collection you want to convert to json into the first parameter,
set the object created by the utility class to the second parameter
to complete the automatic disconnection. Get rid of dead cycles