用于前端角度应用的Spring Boot微服务中的响应编码

时间:2017-12-12 06:51:42

标签: spring-boot http-status-code-404 microservices

我正在使用微服务架构创建我的Web应用程序。这里的前端应用程序,angular 2将与使用spring MVC,spring boot和spring Data JPA开发的后端微服务进行通信。

  • 我的困惑在于,我在我的存储库中添加了方法,比如findbyusername,findbylastname等。在这里,我需要用HTTP状态代码来回馈这个结果。意味着200 Ok,400 Bad request,401 Unauthorized etc.我如何用我的结果编码这些状态代码?当我返回findbyusername结果时,我需要添加200 ok的结果。
  • 此外,我需要将结果作为JSON格式传输,因为angular将数据解析为JSON格式。

这里我的样本控制器操作只有这样,

@CrossOrigin(origins = "http://localhost:4200")
@RequestMapping(value = "/checkAuthentication", method = RequestMethod.POST)
public String checkLoginByName(@RequestBody Users user) throws Exception{

    ObjectMapper mapper = new ObjectMapper();
    Users useObj1 = userRepo.findByUsernameAndPassword(user.username,user.password);
    return(mapper.writeValueAsString(useObj1));

}

在这里我还需要添加状态。任何人都可以帮我澄清这个状态添加问题吗?

1 个答案:

答案 0 :(得分:1)

尝试返回ResponseEntity:

@CrossOrigin(origins = "http://localhost:4200")
@RequestMapping(value = "/checkAuthentication", method = RequestMethod.POST)
public ResponseEntity checkLoginByName(@RequestBody Users user) throws Exception{

  ObjectMapper mapper = new ObjectMapper();
  Users useObj1 = userRepo.findByUsernameAndPassword(user.username,user.password);
  return ResponseEntity<>(mapper.writeValueAsString(useObj1), HttpStatus.OK);

}