我的REST api中有一些返回void的方法。默认情况下,球衣设置204用于这种响应。我知道如果我返回任何非null对象响应是200,但是,我想将状态代码设置为200而无需修改这些方法。我怎样才能做到这一点?
答案 0 :(得分:4)
如果您不介意将每204个响应覆盖到200,那么您可以使用过滤器:
DynamicFeature
<强>更新强>
如果您更喜欢可自定义的解决方案,则可以使用注释和import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
@Target(METHOD)
@Retention(RUNTIME)
public @interface ResponseStatus {
int value() default 200;
}
激活过滤器。
注释:
import java.io.IOException;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
public class OverrideResponseStatusFilter implements ContainerResponseFilter {
private final int statusCode;
public OverrideResponseStatusFilter(int statusCode) {
this.statusCode = statusCode;
}
@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException {
responseContext.setStatus(statusCode);
}
}
过滤器:
import javax.ws.rs.container.DynamicFeature;
import javax.ws.rs.container.ResourceInfo;
import javax.ws.rs.core.FeatureContext;
import javax.ws.rs.ext.Provider;
@Provider
public class ResponseStatusDynamicFeature implements DynamicFeature {
@Override
public void configure(ResourceInfo resourceInfo, FeatureContext context) {
ResponseStatus responseStatus = (ResponseStatus) resourceInfo.getResourceMethod().getAnnotation(ResponseStatus.class);
if (responseStatus != null) {
context.register(new OverrideResponseStatusFilter(responseStatus.value()));
}
}
}
DynamicFeature:
@ResponseStatus(200)
最后使用@GET
@Path("/nothing")
@ResponseStatus(200)
public void nothing() {
}
注释您的资源方法:
Session_End