ResponseEntity状态码异常:手动设400却始终返回200求助
问题分析与解决
核心问题
你在使用JAX-RS注解(@GET、@Path)的同时,返回了Spring框架的ResponseEntity类。JAX-RS规范并不识别Spring的ResponseEntity,它会把这个对象当作普通业务返回值序列化,不会解析其中的状态码和头信息,所以无论你怎么设置,响应状态码都会默认是200。
另外你手动添加的#status#自定义请求头完全多余,框架不会通过这个头识别状态码。
解决方案
根据你的技术栈选择对应处理方式:
方式一:改用JAX-RS原生响应处理
JAX-RS提供了Response类来构建带状态码的响应,替换Spring的ResponseEntity即可:
@GET @Path("/tipoArchivos/{id}") public Response getTipoArchivos(@PathParam("id") String idProceso) throws Exception { List<TipoArchivoDTO> respuesta = tramiteInt.getAttachmentTypes(idProceso); if (respuesta == null) { return Response.status(Response.Status.BAD_REQUEST) .entity("El codigo del proceso solo debe contener tres caracteres en mayuscula") .build(); } return Response.ok(respuesta).build(); }
通过Response.status()指定状态码,entity()设置响应体,build()生成最终响应对象,JAX-RS会正确解析并返回对应状态码。
方式二:改用Spring MVC注解
如果想继续使用Spring的ResponseEntity,需要把JAX-RS注解替换为Spring MVC的注解:
@GetMapping("/tipoArchivos/{id}") public ResponseEntity<?> getTipoArchivos(@PathVariable("id") String idProceso) throws Exception { Optional<List<TipoArchivoDTO>> respuesta = Optional.ofNullable(tramiteInt.getAttachmentTypes(idProceso)); if (!respuesta.isPresent()) { return new ResponseEntity<>("El codigo del proceso solo debe contener tres caracteres en mayuscula", HttpStatus.BAD_REQUEST); } return new ResponseEntity<>(respuesta.get(), HttpStatus.OK); }
使用@GetMapping替换@GET,@PathVariable替换@PathParam,Spring MVC会正确识别ResponseEntity中的状态码配置。
内容的提问来源于stack exchange,提问作者Nicolas Montero
相关产品推荐
相关产品推荐

