Ответ.JAVA

Программисты JAVA общаются здесь
Anonymous
 Ответ.

Сообщение Anonymous »

Я разрабатываю контроллер в Spring Boot. В случае, если элемент не найден в БД, я хотел бы воскресить ответную реакцию с помощью http -кода типа httpstatus.not_found, но также и сообщением, что элемент не был найден. Следующий метод работает, но возвращает только httpstatus.not_found. < /P>
import org.springframework.http.ResponseEntity;

@GetMapping(
value = "/plants/{id}",
produces = MediaType.APPLICATION_JSON_VALUE
)
public ResponseEntity getPlantById(@PathVariable("id") UUID id){
Optional responsePlantDTOOptional = service.getPlantById(id);
return responsePlantDTOOptional.map(
responsePlantVocDTO -> ResponseEntity
.status(HttpStatus.FOUND)
.body(responsePlantVocDTO))
.orElse(
ResponseEntity.notFound().build()
);
}
< /code>
Я пробовал другие решения, но я получаю следующую ошибку: Требуемый тип:
responseentity, предоставление: responseentity < /em> < /p>
@GetMapping(
value = "/plants/{id}",
produces = MediaType.APPLICATION_JSON_VALUE
)
public ResponseEntity getPlantById(@PathVariable("id") UUID id){
Optional responsePlantDTOOptional = service.getPlantById(id);
return responsePlantDTOOptional.map(
responsePlantVocDTO -> ResponseEntity
.status(HttpStatus.FOUND)
.body(responsePlantVocDTO))
.orElse(
// ResponseEntity.notFound().build()
ResponseEntity.status(HttpStatus.NOT_FOUND).body("My message")
);
}

update : это мой контроллер
import jakarta.validation.Valid;
import org.cnr.plantvocdb.dto.PlantInfoDTO;
import org.cnr.plantvocdb.dto.RequestPlantVocDTO;
import org.cnr.plantvocdb.dto.ResponsePlantVocDTO;
import org.cnr.plantvocdb.service.PlantsVocService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;
import java.util.UUID;

@RestController
@RequestMapping("/api/v1/voc")
public class PlantsVocController {

private final PlantsVocService service;

@Autowired
public PlantsVocController(PlantsVocService service) {

this.service = service;
}

/*
* GETs
* */

@GetMapping(
value = "/plants",
produces = MediaType.APPLICATION_JSON_VALUE
)
public List getPlantsVocInfo(){
return service.getAllPlantsInfo();
}

/**
* Get Plant Voc by ID
*/
@GetMapping(
value = "/plants/id/{id}",
produces = MediaType.APPLICATION_JSON_VALUE
)
public ResponseEntity getPlantById(@PathVariable("id") UUID id){
Optional optionalResponsePlantVocDTO = service.getPlantById(id);
return optionalResponsePlantVocDTO.map(
responsePlantVocDTO -> ResponseEntity
.status(HttpStatus.FOUND)
.body(responsePlantVocDTO))
.orElse(ResponseEntity.notFound().build());
}

/**
* Get Plant Voc by IPNI (International Plant Names Index) code
*/
@GetMapping(
value = "/plants/ipni/{ipni}",
produces = MediaType.APPLICATION_JSON_VALUE
)
public ResponseEntity getPlantByIpni(@PathVariable("ipni") String ipni){
Optional optionalResponsePlantVocDTO = service.getPlantByIpni(ipni);
return optionalResponsePlantVocDTO.map(
responsePlantVocDTO -> ResponseEntity
.status(HttpStatus.FOUND)
.body(responsePlantVocDTO))
.orElse(ResponseEntity.notFound().build());
}

@GetMapping(
value = "/plants/always-emitters",
produces = MediaType.APPLICATION_JSON_VALUE
)
public List getPlantsAlwaysEmitter(){
return service.getAlwaysEmitters();
}

@GetMapping(
value = "/plants/never-emitters",
produces = MediaType.APPLICATION_JSON_VALUE
)
public List getPlantsNeverEmitter(){
return service.getNeverEmitters();
}

@GetMapping(
value = "/plants/mixed-emitters",
produces = MediaType.APPLICATION_JSON_VALUE
)
public List getPlantsMixedEmitter(){
return service.getMixedEmitters();
}

/*
* POSTs
* */

@PostMapping(
value = "/plants",
consumes = MediaType.APPLICATION_JSON_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE
)
public ResponseEntity postNewPlant(
@RequestBody
@Valid
RequestPlantVocDTO plantDTO
){
System.out.println("ciao");
String name = plantDTO.getName();

ResponsePlantVocDTO newPlant = service.createPlantVoc(plantDTO);
return ResponseEntity
.status(HttpStatus.CREATED)
.body(newPlant);
}

}


Подробнее здесь: https://stackoverflow.com/questions/794 ... boot-contr

Вернуться в «JAVA»