I have this REST API that receives a single Student in order to be saved. The problem that i have in the controller is that i want to receive this json and converted to my StudentDTO but also being validated at the same time using the @Valid annotation but it doesn't work, it just keeps going.
This is my controller:
package com.controllers.usersapi;
import com.dto.usersapi.StudentDTO;
import com.services.usersapi.StudentApiService;
import com.services.usersapi.StudentApiServiceImpl;
import com.utils.OurDataSource;
import org.springframework.web.bind.annotation.RequestBody;
import javax.validation.Valid;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.Map;
@Path("users")
public class StudentApiRestController {
@POST
@Path("/students")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response createNewStudents(@Valid @RequestBody StudentDTO studentDTO) {
return OurDataSource.evalEm(entityManager -> {
Map<String, Object> studentResultsMap;
StudentApiService studentApiService = new StudentApiServiceImpl(entityManager);
studentResultsMap = studentApiService.saveStudent(studentDTO);
return Response.status(Response.Status.CREATED).entity(studentResultsMap).build();
});
}
}
This is my DTO
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
public class StudentDTO {
@UniqueEmail
@NotNull
private String emailAddress;
@Min(2)
@NotNull
private String firstName;
@Min(2)
@NotNull
private String lastName;
@Min(2)
@NotNull
private String loginId;
@Min(2)
@NotNull
private String techId;
This is the json that i use
{
"emailAddress": "dvanderlinde@gmaill.com",
"firstName": "Dutch",
"lastName": "Van Der Linde",
"loginId": "dvanderlindeeee",
"id": "DVDL200000"
}
ExceptionMapper
import com.google.gson.JsonObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
@Provider
public class DefaultExceptionMapper implements ExceptionMapper<Exception> {
private static final Logger log = LoggerFactory.getLogger(DefaultExceptionMapper.class);
@Override
public Response toResponse(Exception e) {
log.error(e.getMessage(), e);
JsonObject error = new JsonObject();
error.addProperty("message", e.getMessage());
return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.entity(error)
.type(MediaType.APPLICATION_JSON)
.build();
}
}