简体   繁体   English

Apache CXF-处理操作中缺少的路径参数

[英]Apache CXF - Handle missing path parameters in an operation

I am using apache cxf for Jax-rs implementation in my project. 我在我的项目中将apache cxf用于Jax-rs实现。 I have a service defined with the following address: http://ip:port/myservice/ {operation} 我有一个使用以下地址定义的服务: http:// ip:port / myservice / {operation}

consider an operation for this server defined as below 考虑此服务器的操作定义如下

@Override
@GET
@Path("operation1/{x}/{y}")
@Produces("application/xml")
public String operation1(@PathParam("x") final String x, @PathParam("y") final String y) {
    return null;
}

In the scenario where the requester makes a request with some operation name that is not defined in myservice, it will return 404 which is expected behavior. 在请求者使用myservice中未定义的某些操作名称发出请求的情况下,它将返回404,这是预期的行为。 But i am getting the same 404 in cases where operation name is correctly requested but path parameters are not. 但是在正确请求操作名称但没有正确输入路径参数的情况下,我得到的是相同的404。 I would like to create a proper error if any of {x} or {y} path param is missing in a request. 如果请求中缺少{x}或{y}路径参数中的任何一个,我想创建一个适当的错误。 But i cannot find a graceful way where i can handle exceptions as per the operations. 但是我无法找到一种优雅的方式来按操作处理异常。 CXF never maps to the operation in such cases. 在这种情况下,CXF永远不会映射到该操作。

I have this exception mapper: 我有这个异常映射器:

public class ClientExceptionMapper implements ExceptionMapper<ClientErrorException> {

@Override
public Response toResponse(final ClientErrorException exception) {
    return Response.status(Response.Status.FORBIDDEN).entity("Invalid request").build();

}

} }

Which will handle all error cases but it doesn't provide any information as to what URL was requested in the exception. 它将处理所有错误情况,但不提供有关异常中请求的URL的任何信息。 Is there a way where i can handle exceptions differently for different operations in cases when path parameters are not defined ? 在未定义路径参数的情况下,有没有一种方法可以针对不同的操作以不同的方式处理异常? For eg: I would like to handle following request with some custom logic defined for operation1 only. 例如:我想使用仅为operation1定义的一些自定义逻辑来处理以下请求。 http://ip:port/myservice/operation1/20 HTTP:// IP:端口/为MyService / operation1 / 20

I see two solutions for your case. 我为您的案例提供了两种解决方案。
1) Move your path params to query param. 1)将路径参数移动到查询参数。 @QueryParam
2) Create a filter and map it to url operation1/* 2)创建一个过滤器并将其映射到url operation1/*

While finding solution for my scenario where i need to validate path parameters, i found this link which suggests a nice workaround for my problem. 在为需要验证路径参数的方案找到解决方案时,我找到了此链接 ,这为解决我的问题提供了一个不错的解决方法。 Although its just a hack and might not be a good idea to implement in existing code, you can consider it if you need to play around with path parameters within your respective operation. 尽管这只是一个小技巧,可能不是在现有代码中实现的好主意,但是如果需要在各自的操作中使用路径参数,可以考虑使用它。

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

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