以下是一个使用Apache Camel的示例,其中包含restConfiguration,choice和jsonpath的代码:
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.model.rest.RestBindingMode;
public class MyRouteBuilder extends RouteBuilder {
@Override
public void configure() throws Exception {
// 配置REST接口
restConfiguration()
.component("servlet")
.bindingMode(RestBindingMode.json)
.dataFormatProperty("prettyPrint", "true")
.port(8080);
// 定义REST接口的路径和方法
rest("/api")
.get("/hello")
.to("direct:hello");
// 处理REST接口的请求
from("direct:hello")
.choice()
.when().jsonpath("$.name == 'John'")
.setBody(constant("Hello John!"))
.otherwise()
.setBody(constant("Hello Guest!"))
.end();
}
}
在这个示例中,我们首先使用restConfiguration
方法配置了REST接口的基本设置,包括使用servlet组件、绑定模式为JSON、数据格式设置为可读性良好的格式(prettyPrint)和端口号为8080。
然后,我们定义了一个GET请求的REST接口路径为/api/hello
,并将其转发到direct:hello
。
最后,在direct:hello
路由上,我们使用了choice
语句来根据JSON中的属性值进行条件判断。在这个示例中,我们使用了jsonpath
表达式$.name == 'John'
来判断请求中的JSON数据中的name
属性是否等于John
。根据判断结果,我们使用setBody
方法设置响应的消息体内容为不同的值。
这只是一个简单的示例,你可以根据自己的需求进行扩展和修改。希望对你有所帮助!