0

I have the code below on my API, it sends back if the users are in my database.im trying to make it return an error 400 when it isn't, but when I make a request on it with de other code below, the status is 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;
}

This is the response

   @Context 
   private HttpServletResponse response;

This is the client side that makes the requisitions;

   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');
  });
  }

 });

It shouldn't change the page when the status comes as 400, but it does

page return

1 Answers1

1

It is necessary to call the flushBuffer() method after setting the status:

Forces any content in the buffer to be written to the client. A call to this method automatically commits the response, meaning the status code and headers will be written.

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

, for example, as follows:

...
HttpServletResponse response;
...

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

Useful related question: JAX-RS — How to return JSON and HTTP status code together?.

Hope this helps.