我在 servlet 中遇到了一些问题,每次我更改下拉菜单中的选项时, 一个不同的值将传递给 servlet,然后它会导致无限循环。当我没有更改下拉列表中的选项(值没有变化)时,没有错误。
这是我的代码:
我的Javascript:
<script>
function loadStaff(){
//dropdown
var positionDropDown = document.getElementById("positionsDropdown");
//value of the drop down
var positionID = positionDropDown.options[positionDropDown.selectedIndex].value;
$.getJSON('loadStaff?positionID=' + positionID, function(data) {
-- no populate code yet
});
}
</script>
我的 AjaxServlet:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String userPath = request.getServletPath();
if (userPath.equals("/loadStaff")) {
String positionID = request.getParameter("positionID");
Position position = positionFacade.find(Integer.parseInt(positionID));
Collection staffCollection = position.getStaffCollection();
List<Staff> staffList = new ArrayList(staffCollection);
String staffListJson = new Gson().toJson(staffList);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(staffListJson);
}
}
调试时。错误出现在行:
String staffListJson = new Gson().toJson(staffList);
输出错误:
> INFO: WebModule[null] ServletContext.log(): The server side
> component of the HTTP Monitor has detected a
> java.lang.StackOverflowError. This happens when there is an infinite
> loop in the web module. Correct the cause of the infinite loop before
> running the web module again.
>
> INFO: The server side component of the HTTP Monitor has detected a
> java.lang.StackOverflowError. This happens when there is an infinite
> loop in the web module. Correct the cause of the infinite loop before
> running the web module again. WARNING:
> StandardWrapperValve[AjaxServlet]: Servlet.service() for servlet
> AjaxServlet threw exception java.lang.StackOverflowError
> WARNING: StandardWrapperValve[AjaxServlet]: Servlet.service() for
> servlet AjaxServlet threw exception java.lang.StackOverflowError at
> sun.util.calendar.ZoneInfo.getOffsets(ZoneInfo.java:248) at
> java.util.GregorianCalendar.computeFields(GregorianCalendar.java:2276)
> at
> java.util.GregorianCalendar.computeFields(GregorianCalendar.java:2248)
> at java.util.Calendar.setTimeInMillis(Calendar.java:1140) at
> java.util.Calendar.setTime(Calendar.java:1106) at
> java.text.SimpleDateFormat.format(SimpleDateFormat.java:955) at
> java.text.SimpleDateFormat.format(SimpleDateFormat.java:948) at
> java.text.DateFormat.format(DateFormat.java:336) at
> com.google.gson.internal.bind.DateTypeAdapter.write(DateTypeAdapter.java:90)
> at
> com.google.gson.internal.bind.DateTypeAdapter.write(DateTypeAdapter.java:41)
> at
> com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:68)
> at
> com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.write(ReflectiveTypeAdapterFactory.java:89)
> at
> com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.write(ReflectiveTypeAdapterFactory.java:195)
> at com.google.gson.Gson$FutureTypeAdapter.write(Gson.java:892) at
> com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:68)
> at
> com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.write(ReflectiveTypeAdapterFactory.java:89)
> at
> com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.write(ReflectiveTypeAdapterFactory.java:195)
> at
> com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:68)
> at
> com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.write(ReflectiveTypeAdapterFactory.java:89)
> at
> com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.write(ReflectiveTypeAdapterFactory.java:195)
> at com.google.gson.Gson$FutureTypeAdapter.write(Gson.java:892) at
> com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:68)
> at
> com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.write(ReflectiveTypeAdapterFactory.java:89)
> at
> com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.write(ReflectiveTypeAdapterFactory.java:195)
> at
> com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:68)
> at
> com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.write(ReflectiveTypeAdapterFactory.java:89)
> at
> com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.write(ReflectiveTypeAdapterFactory.java:195)
> at com.google.gson.Gson$FutureTypeAdapter.write(Gson.java:892)
我还注意到这个跟踪只是堆栈跟踪的重复输出;
编辑: 员工类
@Entity
public class Staff implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "id")
private Integer id;
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 45)
@Column(name = "last_name")
private String lastName;
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 45)
@Column(name = "first_name")
private String firstName;
@Size(max = 45)
@Column(name = "middle_name")
private String middleName;
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 6)
@Column(name = "gender")
private String gender;
@Basic(optional = false)
@NotNull
@Column(name = "date_of_birth")
@Temporal(TemporalType.DATE)
private Date dateOfBirth;
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 45)
@Column(name = "nationality")
private String nationality;
@Basic(optional = false)
@NotNull
@Column(name = "date_hired")
@Temporal(TemporalType.TIMESTAMP)
private Date dateHired;
@Size(max = 20)
@Column(name = "status")
private String status;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "staff")
private Collection<StaffApointments> staffApointmentsCollection;
@OneToOne(cascade = CascadeType.ALL, mappedBy = "staff")
private StaffContact staffContact;
@JoinColumn(name = "account_id", referencedColumnName = "id")
@ManyToOne(optional = false)
private Account accountId;
@JoinColumn(name = "position_id", referencedColumnName = "id")
@ManyToOne(optional = false)
private Position positionId;
public Staff() {
}
public Staff(Integer id) {
this.id = id;
}
public Staff(Integer id, String lastName, String firstName, String gender, Date dateOfBirth, String nationality, Date dateHired) {
this.id = id;
this.lastName = lastName;
this.firstName = firstName;
this.gender = gender;
this.dateOfBirth = dateOfBirth;
this.nationality = nationality;
this.dateHired = dateHired;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getMiddleName() {
return middleName;
}
public void setMiddleName(String middleName) {
this.middleName = middleName;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public Date getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(Date dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public String getNationality() {
return nationality;
}
public void setNationality(String nationality) {
this.nationality = nationality;
}
public Date getDateHired() {
return dateHired;
}
public void setDateHired(Date dateHired) {
this.dateHired = dateHired;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
@XmlTransient
public Collection<StaffApointments> getStaffApointmentsCollection() {
return staffApointmentsCollection;
}
public void setStaffApointmentsCollection(Collection<StaffApointments> staffApointmentsCollection) {
this.staffApointmentsCollection = staffApointmentsCollection;
}
public StaffContact getStaffContact() {
return staffContact;
}
public void setStaffContact(StaffContact staffContact) {
this.staffContact = staffContact;
}
public Account getAccountId() {
return accountId;
}
public void setAccountId(Account accountId) {
this.accountId = accountId;
}
public Position getPositionId() {
return positionId;
}
public void setPositionId(Position positionId) {
this.positionId = positionId;
}
@Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Staff)) {
return false;
}
Staff other = (Staff) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
@Override
public String toString() {
return "entity.Staff[ id=" + id + " ]";
}
}
这也是 Position 类:
@Entity
public class Position implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "id")
private Integer id;
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 45)
@Column(name = "name")
private String name;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "positionId")
private Collection<Staff> staffCollection;
public Position() {
}
public Position(Integer id) {
this.id = id;
}
public Position(Integer id, String name) {
this.id = id;
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@XmlTransient
public Collection<Staff> getStaffCollection() {
return staffCollection;
}
public void setStaffCollection(Collection<Staff> staffCollection) {
this.staffCollection = staffCollection;
}
@Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Position)) {
return false;
}
Position other = (Position) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
@Override
public String toString() {
return "entity.Position[ id=" + id + " ]";
}
}
编辑 2:
除了 staffCollection 之外,我在 staff 类的属性中添加了 @expose。但我仍然有 1 个问题。每次选择下拉列表中的第一个值(值= 1)时,它仍然会出现无限循环错误。谁能帮帮我?
编辑 3:
修复了!我添加了 final GsonBuilder builder = new GsonBuilder(); builder.excludeFieldsWithoutExposeAnnotation();作为一个整体。现在可以了
最佳答案
问题是每个Staff对象包含一个包含 Collection 的 Position 对象的 Staff对象,每个对象包含一个 Collection的 Staff再次对象等。GSON 将永远继续走这棵树,因为它永远不会停止。
要解决它,您可以查看 this 的答案。问题。
关于java - Servlet Gson().toJson 死循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24094130/
我脑子里浮现出一些关于一种新编程语言的想法,所以我想我会尝试实现它。一位friend建议我尝试使用Treetop(Rubygem)来创建一个解析器。Treetop的文档很少,我以前从未做过这种事情。我的解析器表现得好像有一个无限循环,但没有堆栈跟踪;事实证明很难追踪到。有人可以指出入门级解析/AST指南的方向吗?我真的需要一些列出规则、常见用法等的东西来使用像Treetop这样的工具。我的语法分析器在GitHub上,以防有人希望帮助我改进它。class{initialize=lambda(name){receiver.name=name}greet=lambda{IO.puts("He
我有多个ActiveRecord子类Item的实例数组,我需要根据最早的事件循环打印。在这种情况下,我需要打印付款和维护日期,如下所示:ItemAmaintenancerequiredin5daysItemBpaymentrequiredin6daysItemApaymentrequiredin7daysItemBmaintenancerequiredin8days我目前有两个查询,用于查找maintenance和payment项目(非排他性查询),并输出如下内容:paymentrequiredin...maintenancerequiredin...有什么方法可以改善上述(丑陋的)代
我真的很习惯使用Ruby编写以下代码:my_hash={}my_hash['test']=1Java中对应的数据结构是什么? 最佳答案 HashMapmap=newHashMap();map.put("test",1);我假设? 关于java-等价于Java中的RubyHash,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/22737685/
我收到这个错误:RuntimeError(自动加载常量Apps时检测到循环依赖当我使用多线程时。下面是我的代码。为什么会这样?我尝试多线程的原因是因为我正在编写一个HTML抓取应用程序。对Nokogiri::HTML(open())的调用是一个同步阻塞调用,需要1秒才能返回,我有100,000多个页面要访问,所以我试图运行多个线程来解决这个问题。有更好的方法吗?classToolsController0)app.website=array.join(',')putsapp.websiteelseapp.website="NONE"endapp.saveapps=Apps.order("
我正在尝试使用boilerpipe来自JRuby。我看过guide从JRuby调用Java,并成功地将它与另一个Java包一起使用,但无法弄清楚为什么同样的东西不能用于boilerpipe。我正在尝试基本上从JRuby中执行与此Java等效的操作:URLurl=newURL("http://www.example.com/some-location/index.html");Stringtext=ArticleExtractor.INSTANCE.getText(url);在JRuby中试过这个:require'java'url=java.net.URL.new("http://www
我只想对我一直在思考的这个问题有其他意见,例如我有classuser_controller和classuserclassUserattr_accessor:name,:usernameendclassUserController//dosomethingaboutanythingaboutusersend问题是我的User类中是否应该有逻辑user=User.newuser.do_something(user1)oritshouldbeuser_controller=UserController.newuser_controller.do_something(user1,user2)我
什么是ruby的rack或python的Java的wsgi?还有一个路由库。 最佳答案 来自Python标准PEP333:Bycontrast,althoughJavahasjustasmanywebapplicationframeworksavailable,Java's"servlet"APImakesitpossibleforapplicationswrittenwithanyJavawebapplicationframeworktoruninanywebserverthatsupportstheservletAPI.ht
这篇文章是继上一篇文章“Observability:从零开始创建Java微服务并监控它(一)”的续篇。在上一篇文章中,我们讲述了如何创建一个Javaweb应用,并使用Filebeat来收集应用所生成的日志。在今天的文章中,我来详述如何收集应用的指标,使用APM来监控应用并监督web服务的在线情况。源码可以在地址 https://github.com/liu-xiao-guo/java_observability 进行下载。摄入指标指标被视为可以随时更改的时间点值。当前请求的数量可以改变任何毫秒。你可能有1000个请求的峰值,然后一切都回到一个请求。这也意味着这些指标可能不准确,你还想提取最小/
HashMap中为什么引入红黑树,而不是AVL树呢1.概述开始学习这个知识点之前我们需要知道,在JDK1.8以及之前,针对HashMap有什么不同。JDK1.7的时候,HashMap的底层实现是数组+链表JDK1.8的时候,HashMap的底层实现是数组+链表+红黑树我们要思考一个问题,为什么要从链表转为红黑树呢。首先先让我们了解下链表有什么不好???2.链表上述的截图其实就是链表的结构,我们来看下链表的增删改查的时间复杂度增:因为链表不是线性结构,所以每次添加的时候,只需要移动一个节点,所以可以理解为复杂度是N(1)删:算法时间复杂度跟增保持一致查:既然是非线性结构,所以查询某一个节点的时候
遍历文件夹我们通常是使用递归进行操作,这种方式比较简单,也比较容易理解。本文为大家介绍另一种不使用递归的方式,由于没有使用递归,只用到了循环和集合,所以效率更高一些!一、使用递归遍历文件夹整体思路1、使用File封装初始目录,2、打印这个目录3、获取这个目录下所有的子文件和子目录的数组。4、遍历这个数组,取出每个File对象4-1、如果File是否是一个文件,打印4-2、否则就是一个目录,递归调用代码实现publicclassSearchFile{publicstaticvoidmain(String[]args){//初始目录Filedir=newFile("d:/Dev");Datebeg