Search code examples
spring-boothttp-status-code-404microservices

Response encoding in Spring Boot micro services for front-end Angular application


I am creating my web application using microservices architecture. Here front-end application, Angular 2 will communicate with back end microservices developing using Spring MVC, Spring Boot and Spring Data JPA.

  • Here my confusion is that I added methods in my repository, like findbyusername, findbylastname etc. And here I need to give back this results with HTTP status codes. Means 200 Ok, 400 Bad request, 401 Unauthorized etc. How I can encode these status code with my results? When I returning findbyusername result, I need to add 200 ok with that result.
  • Also I need to transfer the result as JSON format, since Angular is parsing data as JSON format.

Here my sample controller action only like this,

@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));

}

Here I need to add status also.


Solution

  • Try returning a 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);
    
    }