REST - java.lang.IllegalStateException:已为此响应调用了getOutputStream()

时间:2017-07-09 07:52:54

标签: java spring rest spring-boot

当我尝试调用GET方法时,我收到了IllegalStateException,我不知道出了什么问题。您可以在下面看到日志。

https://pastebin.com/EC6CABcU - 日志

package com.medicalsystem.controller;

import com.medicalsystem.model.Admission;
import com.medicalsystem.service.AdmissionService;
import com.medicalsystem.service.PatientService;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@AllArgsConstructor(onConstructor = @__(@Autowired))
public class AdmissionController {

    private AdmissionService admissionService;
    private PatientService patientService;


    @RequestMapping(value = "/admission/{admissionId}", method = RequestMethod.GET)
    public ResponseEntity<Admission> getAdmission(@PathVariable("admissionId") int admissionId) {
        if (!admissionService.exists(admissionId)) {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
        Admission admission = admissionService.getById(admissionId);
        return new ResponseEntity<>(admission, HttpStatus.OK);
    }


    @RequestMapping(value = "/admission", method = RequestMethod.PUT)
    public ResponseEntity<String> updateAdmission(@RequestBody Admission admission) {
        admissionService.saveOrUpdate(admission);
        return new ResponseEntity<>("Admission successfully added", HttpStatus.OK);
    }
}

1 个答案:

答案 0 :(得分:0)

在我看来,录取是一个实体课程。

import com.medicalsystem.model.Admission;

Admission admission = admissionService.getById(admissionId);

直接从您的Web服务返回Entity不是一个好习惯。 由于实体可以是实时的和管理的,因此对getter方法特别映射的字段的任何调用都将导致加载相关实体。并且由于bean到json序列化器将以递归方式调用所有getter方法来构造json字符串,因此当实体相互引用时,它将以循环调用结束。您可以在日志中清楚地看到(StackOverflowError)

java.lang.StackOverflowError: null
at java.lang.ClassLoader.defineClass1(Native Method) ~[na:1.8.0_131]
at java.lang.ClassLoader.defineClass(ClassLoader.java:763) ~[na:1.8.0_131]
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142) ~[na:1.8.0_131]
at java.net.URLClassLoader.defineClass(URLClassLoader.java:467) ~[na:1.8.0_131]
at java.net.URLClassLoader.access$100(URLClassLoader.java:73) ~[na:1.8.0_131]
at java.net.URLClassLoader$1.run(URLClassLoader.java:368) ~[na:1.8.0_131]
at java.net.URLClassLoader$1.run(URLClassLoader.java:362) ~[na:1.8.0_131]
at java.security.AccessController.doPrivileged(Native Method) ~[na:1.8.0_131]
at java.net.URLClassLoader.findClass(URLClassLoader.java:361) ~[na:1.8.0_131]
at java.lang.ClassLoader.loadClass(ClassLoader.java:424) ~[na:1.8.0_131]
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335) ~[na:1.8.0_131]
at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ~[na:1.8.0_131]

创建一个响应Bean并定义要返回的字段,并将您需要的数据从实体传输到响应bean。