Java 如何在REST中验证路径变量

Java 如何在REST中验证路径变量,java,rest,spring-mvc,path-parameter,Java,Rest,Spring Mvc,Path Parameter,我的问题是,如果使用@PathParam,如何验证请求参数 例如,我有两个请求参数,name和id path is localhost:/.../search/namevalue/idvalue 如果用户提交了名称或id的空格,我应该发送一个响应,说明名称是必需的/id是必需的 如果我使用@QueryParam,我可以进行验证,但是如果我必须使用pathvariables,我不知道如何进行验证 如果我只是使用http:/localhost:/…/search/namevalue或http:/l

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

例如,我有两个请求参数,name和id

path is localhost:/.../search/namevalue/idvalue
如果用户提交了名称或id的空格,我应该发送一个响应,说明名称是必需的/id是必需的

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

如果我只是使用
http:/localhost:/…/search/namevalue
http:/localhost:/…/search/idvalue
http:/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 }
@控制器
@路径(“/customer”)
公共类CustomerController扩展BaseController实现客户{
@凌驾
@得到
@产生({“application/json”、“application/xml”})
@路径(“/search/{name}/{id}/”)
公众响应搜索客户详细信息(
@PathParam(“名称”)字符串名称,
@PathParam(“id”)整数id){
ResponseBuilder response=null;
CustomerValidations validations=(CustomerValidations)getAppContext()
.getBean(CustomerValidations.class);
CustomerResponse CustomerResponse=新CustomerResponse();
CustomerService CustomerService=(CustomerService)getAppContext()
.getBean(CustomerService.class);
试一试{
validations.searchCustomerDetailsValidation(
姓名、id、客户响应);
如果(customerResponse.getErrors().size()=0){
CustomerDetails=customerService
.searchCustomerDetailsService(名称、id);
如果(详细信息==null){
response=response.status(response.status.NO_内容);
}否则{
customerResponse.setCustomerDetails(详细信息);
response=response.status(response.status.OK).entity(
客户响应);
}
}否则{
response=response.status(response.status.BAD_请求)。实体(
客户响应);
}
}
捕获(例外e){
LOGGER.error(例如getMessage());
response=response.status(response.status.INTERNAL\u SERVER\u错误);
}
返回response.build();
} }
@组成部分
@范围(“原型”)
公共类CustomerValidations{
公共无效搜索CustomerDetailsValidation(
字符串名,整数id,
客户响应(客户响应){
if(id==null){
customerResponse.getErrors().add(
新的ValidationError(“错误的请求”,
“无效id”);
}
if(name==null)
||(名称!=null&&name
.trim().length()=0){
customerResponse.getErrors().add(
新的ValidationError(“错误的请求”、“无效的id”);
}
} }
@XmlRootElement
公共类CustomerResponse{
私人客户详情客户详情;
私有列表错误=新建ArrayList();
//setters和getter}
公共类验证错误{
私有字符串状态;
私有字符串消息;
公共验证错误(){
}
公共验证错误(字符串状态、字符串消息){
超级();
这个状态=状态;
this.message=消息;
}
//setters和getter}

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

不过,我不确定您为什么要验证这些“缺失”的请求路径-看起来这个端点是用来作为查询端点的,所以我建议您使用
@RequestParam
/query参数来更全面地描述您正在尝试的搜索。
search/{name}/{id}
的路径将建议一个永久存在于该URL的特定资源,尽管在本例中,您正在该控制器上查询客户

我建议您完全删除
/search
路径,只需将查询参数映射到客户控制器的“根”上,就可以得到

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

请添加您的代码和stacktrace。@Jens我添加了代码,谢谢!