JAX-RS Web 服务如何只接受在请求正文中发送的表单参数?
How can a JAX-RS web service only accept form parameters that are sent in the request body?
假设我有以下 JAX-RS 网络服务:
public class HelloService {
@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.TEXT_PLAIN)
public String getMessage(@FormParam("name") String name) {
return "Hello, " + name + "!";
}
}
此 Web 服务将接受表单参数,无论它们是在请求正文中发送还是在 URL 中发送(例如 http://foo.bar/baz?name=qux
)。
有没有一种方法可以将 Web 服务配置为仅接受请求正文中发送的表单参数?
您可以尝试 ContainerRequestFilter
,如下所示:
@Provider
public class QueryParametersFilter implements ContainerRequestFilter {
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
String query = requestContext.getUriInfo().getRequestUri().getQuery();
if (query != null && !query.isEmpty()) {
requestContext.abortWith(
Response.status(Status.BAD_REQUEST)
.entity("Parameters not allowed in the query string")
.build());
}
}
}
可以根据您的需要定制实现。
重要:上面定义的过滤器是全局的,即对所有资源方法都会执行。要将此过滤器绑定到一组方法,请选中此 .
对于动态绑定,您也可以尝试 DynamicFeature
。
假设我有以下 JAX-RS 网络服务:
public class HelloService {
@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.TEXT_PLAIN)
public String getMessage(@FormParam("name") String name) {
return "Hello, " + name + "!";
}
}
此 Web 服务将接受表单参数,无论它们是在请求正文中发送还是在 URL 中发送(例如 http://foo.bar/baz?name=qux
)。
有没有一种方法可以将 Web 服务配置为仅接受请求正文中发送的表单参数?
您可以尝试 ContainerRequestFilter
,如下所示:
@Provider
public class QueryParametersFilter implements ContainerRequestFilter {
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
String query = requestContext.getUriInfo().getRequestUri().getQuery();
if (query != null && !query.isEmpty()) {
requestContext.abortWith(
Response.status(Status.BAD_REQUEST)
.entity("Parameters not allowed in the query string")
.build());
}
}
}
可以根据您的需要定制实现。
重要:上面定义的过滤器是全局的,即对所有资源方法都会执行。要将此过滤器绑定到一组方法,请选中此
对于动态绑定,您也可以尝试 DynamicFeature
。