0

My Question is How can I validate request parameters if I use @PathParam.

For instance I have two request parameters, name and id

path is localhost:/.../search/namevalue/idvalue

if a user submits blanks for name or id I should send a response mentioning that name is required/ id is required.

I could do the validations if I use @QueryParam, but I'm not sure how to do it if I have to use pathvariables.

If I just test using http:/localhost:/.../search/namevalue orhttp:/localhost:/.../search/idvalue or http:/localhost:/.../search/ it's throwing servlet exception.

Below is the code, if i use QueryParams validations work just fine, Please let me know the approach when i use pathparam

 @Controller
 @Path("/customer")
 public class CustomerController extends BaseController implements Customer {

@Override
@GET
@Produces({ "application/json", "application/xml" })
@Path("/search/{name}/{id}/")
public Response searchCustomerDetails(
        @PathParam("name") String name,
        @PathParam("id") Integer id) {

    ResponseBuilder response = null;
    CustomerValidations validations = (CustomerValidations) getAppContext()
            .getBean(CustomerValidations.class);
    CustomerResponse customerResponse = new CustomerResponse();
    CustomerService customerService = (CustomerService) getAppContext()
            .getBean(CustomerService.class);

    try {
        validations.searchCustomerDetailsValidation(
                name, id,customerResponse);

        if (customerResponse.getErrors().size() == 0) {
            CustomerDetails details = customerService
                    .searchCustomerDetailsService(name, id);
            if (details == null) {
                response = Response.status(Response.Status.NO_CONTENT);

            } else {
                customerResponse.setCustomerDetails(details);
                response = Response.status(Response.Status.OK).entity(
                        customerResponse);
            }
        } else {

            response = Response.status(Response.Status.BAD_REQUEST).entity(
                    customerResponse);
        }
    }

    catch (Exception e) {
        LOGGER.error(e.getMessage());
        response = Response.status(Response.Status.INTERNAL_SERVER_ERROR);

    }

    return response.build();
} }


@Component
@Scope("prototype")
public class CustomerValidations {

public void searchCustomerDetailsValidation(
        String name, Integer id,
        CustomerResponse customerResponse) {


    if (id == null) {

        customerResponse.getErrors().add(
                new ValidationError("BAD_REQUEST",
                        ""invalid id));
    }

    if (name== null
            || (name!= null && name
                    .trim().length() == 0)) {

        customerResponse.getErrors().add(
                new ValidationError("BAD_REQUEST", "invalid id"));
    }
} }

@XmlRootElement
 public class CustomerResponse {

private CustomerDetails customerDetails;
private List<ValidationError> errors = new ArrayList<ValidationError>();

//setters and getters }



public class ValidationError {

private String status;
private String message;


public ValidationError() {

}

public ValidationError(String status, String message) {
    super();
    this.status = status;
    this.message = message;
}
//setters and getters }
user3808439
  • 3
  • 1
  • 4

1 Answers1

1

You're receiving an exception because you have no methods mapped to @Path("/search/{foo}/") or @Path("/search/"), so you should be getting a default 404 response as these paths are not really defined.

I'm not sure why you would want to validate these "missing" request paths though - it looks like this endpoint is intended to be used as a query endpoint so I'd suggest you use @RequestParam/query parameters to more RESTfully describe the search you're attempting. A path of search/{name}/{id} would suggest a specific resource which permanently lives at this URL, though in this case you're querying for customers on this controller.

I would propose you drop the /search path completely and just map query parameters onto the "root" of the Customer controller, so you get something like

@Controller
@Path("/customer")
public class CustomerController extends BaseController implements Customer {

    @GET
    @Produces({"application/json", "application/xml"})
    public Response searchCustomerDetails(
            @RequestParam("name") String name,
            @RequestParam("id") Integer id) {

            // Returns response with list of links to /customer/{id} (below)

    }


    @GET
    @Produces({"application/json", "application/xml"})
    @Path("/{id}")
    public Response getCustomerDetails(@PathVariable("id") String id) {

            // GET for specific Customer
    }
}
Ross Taylor-Turner
  • 3,687
  • 2
  • 24
  • 33