可以通过编写自定义控制器并使用Spring AOP拦截器来修改API响应。以下是一些示例代码:
首先,创建一个自定义控制器:
@RestController
public class CustomController {
@Autowired
private FhirContext fhirContext;
@RequestMapping(value = "/Patient/{id}", method= RequestMethod.GET, produces= {"application/json", "application/fhir+json"})
public ResponseEntity<String> getPatient(@PathVariable(value= "id") String id, HttpServletRequest request, HttpServletResponse response) throws IOException {
IParser parser = fhirContext.newJsonParser();
parser.setPrettyPrint(true);
Patient patient = new Patient();
patient.setId(id);
patient.addName().setFamily("Smith").addGiven("John");
String responseString = parser.encodeResourceToString(patient);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
return new ResponseEntity<String>(responseString, headers, HttpStatus.OK);
}
}
然后,创建一个Spring AOP拦截器:
@Aspect
@Configuration
public class ResponseInterceptor {
@Autowired
private FhirContext fhirContext;
@Around("execution(* org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handle(..))")
public Object modifyResponse(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
Object returnValue = proceedingJoinPoint.proceed();
if (returnValue instanceof ResponseEntity) {
ResponseEntity<?> responseEntity = (ResponseEntity<?>) returnValue;
if (responseEntity.getBody() instanceof String) {
String body = (String) responseEntity.getBody();
// Perform modifications on the response body
Patient patient = (Patient) fhirContext.newJsonParser().parseResource(body);
patient.addTelecom().setSystem(ContactPoint.ContactPointSystem.PHONE).setValue("555-555-5555");
String modifiedBody = fhirContext.newJsonParser().encodeResourceToString(patient);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
return new ResponseEntity<String>(modifiedBody, headers, responseEntity.getStatusCode());
}
}
return returnValue;
}
}
这将修改返回的患者资源并添加一个电话号码。
请注意,上述代码示例仅适用于返回JSON的情况。如果您需要在响应中生成XML,则需要为XML创建相同的代码。