gpt4 book ai didi

java - 响应未设置状态 400 Jersey

转载 作者:行者123 更新时间:2023-12-02 12:21:57 24 4
gpt4 key购买 nike

我的 API 上有下面的代码,如果用户在我的数据库中,它会发回。当用户不在我的数据库中时,我会尝试让它返回错误 400,但是当我使用其他代码对其发出请求时下面,状态为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

最佳答案

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

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).

例如如下:

...
HttpServletResponse response;
...

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

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

希望这有帮助。

关于java - 响应未设置状态 400 Jersey,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45701598/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com