当我创建GET响应时,我有Stackoveflow错误
回答控制器
@Controller
public class TaskViewController {
@Autowired
private TaskService taskService;
@RequestMapping(value = "/task/view", method = RequestMethod.GET)
public @ResponseBody
AjaxResponseBody getTask(@RequestParam String text) {
int id;
AjaxResponseBody result = new AjaxResponseBody();
Task task;
System.out.println(text);
try {
id = Integer.parseInt(text);
}
catch (Exception e) {
result.setMsg("Invalid task number");
return result;
}
task = taskService.findById(id);
if (task == null){
result.setMsg("Task not found");
return result;
}
result.setTask(task);
return result;
}
}
他使用类AjaxResponseBody作为答案
public class AjaxResponseBody {
private String msg;
private Task task;
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Task getTask() {
return task;
}
public void setTask(Task task) {
this.task = task;
}
}
当这个控制器工作时,我抓住了
2017-11-24 10:47:10.514 WARN 1448 --- [nio-8080-exec-4] .w.s.m.s.DefaultHandlerExceptionResolver : Failed to write HTTP message: org.springframework.http.converter.HttpMessageNotWritableException: Could not write content: Infinite recursion (StackOverflowError) (through reference chain: tracker.models.Project_$$_jvstd06_4["user"]->tracker.models.User_$$_jvstd06_5["watched_project"]->tracker.models.Project_$$_jvstd06_4["user"]->tracker.models.User_$$_jvstd06_5["watched_project"]->tracker.models.Project_$$_jvstd06_4["user"]->tracker.models.User_$$_jvstd06_5["watched_project"]->tracker.models.Project_$$_jvstd06_4["user"]->tracker.models.User_$$_jvstd06_5["watched_project"]->
我理解这是因为模型User和model Project之间存在链接。 Model User有一个可选字段“watched_project”。
@Entity
@Table(name = "users")
public class User {
@ManyToOne(fetch = FetchType.LAZY)
private Project watched_project;
public Project getWatched_project() {
return watched_project;
}
public void setWatched_project(Project watched_project) {
this.watched_project = watched_project;
}
模型项目有字段而不是字段“作者”:
@Entity
@Table(name = "projects")
public class Project {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private int id;
@Column(nullable = false)
@NotEmpty(message = "*Please provide project name")
private String projectName;
@ManyToOne(optional = false, fetch = FetchType.EAGER)
private User user;
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
我如何中止itteration?或者任何方式?
答案 0 :(得分:2)
JSON序列化尝试序列化对象,并且您有循环引用。关于它,有很多问题。如果您使用的是杰克逊,则可以对@JsonIgnore
内的Project
对象或User
内的User
对象使用注释Project
。
您也可以在this回答中使用@JsonManagedReference
和@JsonBackReference
。