AndreFontaine February 2016

Spring java ResponseEntity<T> with multiple parameter types

I'm working with java and Spring MVC, In the first version of the app I was response with a ResponseEntity<String> and where I haved and error I returned something like return new ResponseEntity<String>(httpErrors.toString(), responseHeaders, HttpStatus.BAD_REQUEST); and when all were right something like return new ResponseEntity<String>(loginResponse.toString(), responseHeaders, HttpStatus.OK);. But now I believe theres is a better way to do it, without using the toString() method, returning the specific object according to the case like this:

@RestController
@RequestMapping("/user")
public class LoginController {

    /** The login service to validate the user. */
    @Autowired
    LoginService loginService;

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public @ResponseBody ResponseEntity<?> validate(@RequestBody final UserLog login) {

        WebUser webUser = loginService.getUserDetails(login.getLogin(), login.getPassword());
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.setContentType(MediaType.APPLICATION_JSON);

        if (webUser == null) {
            HttpErrors httpErrors = new HttpErrors(ApiCommonResources.ERROR_402, "error" + "." + ApiCommonResources.ERROR_402, ApiCommonResources.ERROR_402_TEXT);
            return new ResponseEntity<HttpErrors>(httpErrors, responseHeaders, HttpStatus.BAD_REQUEST);
        }

        List<Account> userAccounts = loginService.getMerchantAccounts(webUser.getMerchantId());

        // Json Web Token builder
        token = "b7d22951486d713f92221bb987347777";

        LoginResponse loginResponse = new LoginResponse(ApiCommonResources.SUCCESS_REQUEST_CODE, token);

        return new ResponseEntity<LoginResponse>(loginResponse, responseHeaders, HttpStatus.OK);

    }

}

The question is how can I create a class that can wraps the

Answers


yUdoDis February 2016

public class Response<T> {

   private int httpStatus;
   private T data;

   //getter and setter consructor

    eg constructors
    public RestResponse(T data){
    this(HTTP_OK,data)
    }

    public RestResponse(int httpStatus,T data){
    this.httpStatus = httpStaus;
    this.data = data;  

  }

Now just use this template for all your response objects (repsone objects can be POJOs too)

return new RestEntity<LoginResponse>(loginResponse,statusCode) //loginResponse object

where LoginResponse is

public class LoginResponse {
private String token;
//getter and setter and constructors.
}

You should take some time to establish a REST contracts (Read about it using google :)) and then just follow through using this basic logic. Java and spring are magic together. Have fun.


pezetem February 2016

maybe try something like this (in my opinion it will be more elegant)

create a method in controller which returns LoginResponse, but firstly perform validation of the input UserLog and once there are any issues, throw a custom exception, which in the end will be caught by the exceptionHandler

take a look at my example controller

@RestController
public class ProductController {
    private ProductRequestValidator productRequestValidator;

    @InitBinder
    public void initBinder(WebDataBinder binder){
        binder.addValidators(productRequestValidator);
    }

    @Autowired
    public ProductController(ProductRequestValidator productRequestValidator, ProductService productService) {
        this.productRequestValidator = productRequestValidator;
    }

    @RequestMapping(value = "/products", method = RequestMethod.GET)
    public List<ProductResponse> retrieveProducts(@Valid @RequestBody ProductRequest requestProduct, BindingResult bindingResult)
            throws ValidationException {

        // validate input and throw exception if any error occured
        if (bindingResult.hasErrors()){
            throw new ValidationException(bindingResult);
        }

        // business logic
        return new ProductRequest();
}

if you want you can check my bitbucket project which has it all implemented:

Post Status

Asked in February 2016
Viewed 2,230 times
Voted 4
Answered 2 times

Search




Leave an answer