如何在REST中验证路径变量

时间:2014-07-05 21:41:21

标签: java rest spring-mvc path-parameter

我的问题是如果我使用@PathParam,我如何验证请求参数。

例如,我有两个请求参数,名称和ID

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

如果用户提交名称或ID的空白,我应该发送一个回复,提到该名称是必需的/ id是必需的。

如果我使用@QueryParam,我可以进行验证,但如果我必须使用pathvariables,我不知道如何做。

如果我只是使用http:/localhost:/.../search/namevaluehttp:/localhost:/.../search/idvaluehttp:/localhost:/.../search/进行测试,则会抛出servlet异常。

下面是代码,如果我使用QueryParams验证工作得很好,请让我知道使用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 }

1 个答案:

答案 0 :(得分:1)

您收到异常是因为没有方法映射到@Path("/search/{foo}/")@Path("/search/"),因此您应该获得默认的404响应,因为这些路径并未真正定义。

我不确定你为什么要验证这些&#34;缺失&#34;请求路径 - 看起来此端点旨在用作查询端点,因此我建议您使用@RequestParam /查询参数来更好地描述您尝试的搜索。路径search/{name}/{id}会建议永久存在于此网址的特定资源,但在这种情况下,您需要查询此控制器上的客户。

我建议你完全放弃/search路径,只需将查询参数映射到&#34; root&#34;客户控制器,所以你得到像

这样的东西
@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
    }
}