0
@PutMapping("/createUser") public String createUser(@RequestBody User user) { User thisValue = repository.findByUsername(user.getUsername()); if thisValue != null { sendResponseHeaders(400, -1); // wont work return "account exist"; } sendResponseHeaders(200, -1); // wont work return "reached here"; } 

com.sun.httpserver that I used before has a sendResponseheaders method and I cant find that on springboot. Is there anyway to accomplish this. Basically what I want it. If I send a json request body with a username that exist then a 400 response error should occur

3 Answers 3

1

You can use org.springframework.http.ResponseEntity.

<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <version>x.x.x.RELEASE</version> </dependency> 

Like this.

@PutMapping("/createUser") public ResponseEntity createUser(@RequestBody User user) { User thisValue = repository.findByUsername(user.getUsername()); if (thisValue != null) { return ResponseEntity.badRequest().build(); } return ResponseEntity.ok().build(); } 

More information

Sign up to request clarification or add additional context in comments.

1 Comment

Then what? Like what is the method
1

In addition to returning an explicit ResponseEntity, you can throw an exception (or allow an exception to escape) that is annotated at the class level with @ResponseStatus. The default Spring MVC configuration will intercept any exception coming out of a controller method and will return an HTTP 500 (general "server error") if it has no annotation or the specified status if it does.

Comments

0

In a normal controller:

@PutMapping("/createUser") public ModelAndView createUser(@RequestBody User user) { ModelAndView mv= new ModelAndView("reached-here"); User thisValue = repository.findByUsername(user.getUsername()); if (thisValue != null) { model.setStatus(HttpStatus.BAD_REQUEST); model.setValueName("account-exist"); }else{ model.setStatus(HttpStatus.OK); } return mv; } 

In a REST controller:

@PutMapping("/createUser") public ResponseEntity<String> createUser(@RequestBody User user) { User thisValue = repository.findByUsername(user.getUsername()); if (thisValue != null) { return new ResponseEntity<String>("account-exist", HttpStatus.BAD_REQUEST); }else{ return new ResponseEntity<String>("reached here", HttpStatus.OK); } } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.