有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Ho在响应对象中设置状态代码400

我使用的是来自javax的响应对象。ws。rs api,即使我可以设置响应之类的状态。状态(响应、状态、错误请求)。build(),返回的响应代码始终为200,响应主体包含statusInfo参数,该参数表示BAD_请求。 有没有办法根据服务器端输入的一些验证将响应代码设置为400


共 (2) 个答案

  1. # 1 楼答案

    不只是设置响应状态,而是从服务层抛出错误,让它传播到控制器。 在控制器中,你可以有

    @Controller
    public class MyService {
        @RequestMapping(value = "your api url path", method = RequestMethod.GET, produces = "application/
        public Response jsonAccounts(HttpServletRequest request,
                HttpServletResponse response) throws Exception {
            return Response.status(Response.Status.BAD_REQUEST).entity("Bad request received").build();
        }
    
        @ExceptionHandler(MyBadException.class)
        @ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = "Bad request Request Exception")
        public void unexpectedError(HttpServletRequest request, Exception 
            log.debug("return HttpStatus.BAD_REQUEST, unexpectedError due to Exception", e);
        }
    }
    
  2. # 2 楼答案

    这对我很有效,我测试过

     @GET
    @Path("/")
    @Produces(MediaType.APPLICATION_JSON)
    public Response getTestResult() {
        logger.info("Requested Test Service");
        try {
            Object result = "";[enter image description here][1]
          return  Response.status(Response.Status.BAD_REQUEST)
                  .entity(result).build();
        } catch (Exception e) {
            return Response.ok("error", e.getMessage()).build();
        }
    
    }