Reputation: 11
I am a newbie in Spring and working on spring restful API for a project.I needed to do validation on the parameters that are passed. I am stucked on that currently. below is what I have in the controller.
@RequestMapping(value = "/processRequest/{username}/{password}/{item}/{reference}/{email}/{amount}/{order_id}/{trxn_id}/{pay_channel}", method = RequestMethod.POST)
public @ResponseBody
JsonResponse processTopupRequest(@PathVariable("username") String username,
@PathVariable("password") String password,
@PathVariable("item") String item, @PathVariable("reference") String reference,
@PathVariable("email") String email, @PathVariable("amount") BigDecimal amount,
@PathVariable("order_id") String orderId, @PathVariable("trxn_id") String transactionId,
@PathVariable("pay_channel") PaymentChannel payChannel) {
JsonResponse response = new JsonResponse();
TopupOrderAPI apiOrder = new TopupOrderAPI(username, password, item, reference, email, amount,orderId, transactionId, payChannel);
}
I am wondering if I am on the right track.And if so can anybody advice how i can do validations on the parameters...especially phoneNumber,email and amount. Thanks much
Upvotes: 1
Views: 4909
Reputation: 34826
First of all I would suggest to get rid of all the path variables. Move them to some sort of DTO object, for example TopUpRequestDto
. Then add JSR-303 validation annotations to that DTO, so it will look something like this:
public class TopUpRequestDto {
@NotBlank
@Size(min = 3, max = 50)
private String username;
private String password;
private String item;
private String email;
private String orderId;
private PaymentChannel paymentChannel;
// Getters and setters
}
Add appropriate validations to all the fields (you can find a list of available JSR-303 annotations in the links below). In the example above I put validations just on a single field to demonstrate the concept.
Then modify your controller method like so:
@RequestMapping(value = "/processTopUpRequest", method = RequestMethod.POST)
public @ResponseBody JsonResponse processTopUpRequest(@RequestBody @Valid TopUpRequestDto dto) {
// your logic
}
When you make a request containing invalid data, Spring will automatically return BAD REQUEST status.
To enable JSR-303 validation just put a JSR-303 provider on the classpath and Spring should take care of the rest. So if you're using Maven for example, just add hibernate-validator
dependency.
Here are some links you might find useful:
Upvotes: 3