本质上,graphql-java-servlet软件模块实现了一个Java Servlet,将GraphQL服务发布为通过HTTP可访问的Web服务。目前,graphql-java-servlet软件模块只支持GraphQL的Query和Mutation操作类型,还不支持subscription操作类型。
graphql-java-servlet软件模块的最新版本是2017.12发布的4.7.0。
1. graphql-java-servlet依赖如下模块
- javax.servlet:javax.servlet-api:3.0.1
- com.graphql-java:graphql-java:6.0
- com.fasterxml.jackson.core:jackson-*:2.8.4
2. 在Maven项目中使用graphql-java-servlet,只要在pom.xml中如下引用
<dependency>
<groupId>com.graphql-java</groupId>
<artifactId>graphql-java-servlet</artifactId>
<version>4.7.0</version>
</dependency>
3. graphql-java-servlet软件模块只是一个Servlet,即只提供了唯一的Web请求路径
虽然只是一个Servlet,但是同时支持HTTP GET/POST请求,而且根据请求参数的不同,可以有多种请求的方式。
1)内部结构查询GET请求
http://localhost:8080/graphql/schema.json
2)GraphQL查询GET请求
http://localhost:8080/graphql/?query={...}
3)GraphQL查询 POST请求
http://localhost:8080/graphql/
{"query":"{hello}"}
4)GraphQL查询(multipart/form-data)POST请求
http://localhost:8080/graphql/
{"graphql": {"query":"{hello}"}}
5)GraphQL查询(multipart/form-data)POST请求
http://localhost:8080/graphql/
{"query": {"{hello}"}}
说明:对于每个请求(可能是query或mutation),可以带参数的"operationName","variables",其中"operationName"是操作的对象,"variables"是操作对象的属性集。
默认请求的HTTP Content-Type为application/json;charset=UTF-8。
4. 在Spring Web应用中使用graphql-java-servlet模块
1)通过graphql-spring-boot模块,间接使用graphql-java-servlet模块,详情请参考graphql-spring-boot,结合GraphQL的Spring Boot Starters类库概述。
2)通过定义Spring bean如下
@Bean
ServletRegistrationBean graphQLServletRegistrationBean(GraphQLSchema schema, ExecutionStrategy executionStrategy, List<GraphQLOperationListener> operationListeners) {
return new ServletRegistrationBean(new SimpleGraphQLServlet(schema, executionStrategy, operationListeners), "/graphql");
}
默认Web请求路径为/graphql。
参考链接:
https://github.com/graphql-java/graphql-java-servlet