响应未设置状态400 Jersey

时间:2017-08-15 21:10:24

标签: java angularjs http jersey httpresponse

我在我的API上有以下代码,如果用户在我的数据库中,它会发回来。我试图让它在没有时返回错误400,但是当我用de其他代码向它发出请求时下面,状态是200

@POST
@Path("/login")
@Consumes("application/json; charset=UTF-8")
@Produces("application/json; charset=UTF-8")
public HashMap<String, Object> login(User userLogin) {
    User user;
    HashMap<String, Object> responsed = new HashMap<>();
    try {

        user = userBO.userExists(userLogin);


        request.getSession().setAttribute("user", user);

        logger.debug("User inserido na session: " + new Date() + " - " + user.toString());
        logger.debug("Session LOGIN: " + new Date() + " - " + request.getSession().hashCode());

        responsed.put("logado", true);
        responsed.put("status",200);

    } catch (Exception e) {
        response.setStatus(Response.Status.BAD_REQUEST.getStatusCode());
        responsed.put("logado", false);
        responsed.put("status",400);
    }

    return responsed;
}

这是回复

   @Context 
   private HttpServletResponse response;

这是发出请购单的客户方;

   angular.module('app').controller('loginController', function($scope, $location, $http) {

 $scope.bruno = () =>{
  $http.post('http://localhost:8080/modeloAPI/auth/login', $scope.user)
  .then(function(response) {
    console.log('deu bom');
    console.log(response);
      $location.path('/dashboard');
  })
  .catch(function(response) {
    console.log('deu ruim');
  });
  }

 });

当状态为400时,它不应该更改页面,但它确实

page return

1 个答案:

答案 0 :(得分:1)

设置状态后需要调用flushBuffer()方法:

  

强制将缓冲区中的任何内容写入客户端。对此方法的调用会自动提交响应,这意味着将写入状态代码和标题。

     

- ServletResponse.flushBuffer() method (Java(TM) EE 7 Specification APIs)

,例如,如下:

...
HttpServletResponse response;
...

response.setStatus(HttpServletResponse.SC_BAD_GATEWAY);
response.flushBuffer();

有用的相关问题:JAX-RS — How to return JSON and HTTP status code together?

希望这有帮助。