繁体   English   中英

如何在REST中验证路径变量

[英]How to validate path variables in REST

我的问题是,如果使用@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 }

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

我不确定您为什么要验证这些“缺失”的请求路径-看起来该端点打算用作查询端点,因此建议您使用@RequestParam / query参数来更RESTful地描述搜索您要尝试的内容。 search/{name}/{id}路径将建议一个永久存在于此URL的特定资源,尽管在这种情况下,您正在此控制器上查询客户。

我建议您完全删除/search路径,然后将查询参数映射到Customer控制器的“根”,这样您将得到类似

@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
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM