gpt4 book ai didi

rest - 返回 OK (200) 而不是 NO_CONTENT (204)

转载 作者:行者123 更新时间:2023-12-04 02:16:31 24 4
gpt4 key购买 nike

我的 REST api 中有几个返回无效的方法。默认情况下,jersey 为此类响应设置 204。我知道如果我返回任何非空对象响应是 200,但是,我想将状态代码设置为 200 而无需修改这些方法。我怎样才能做到这一点?

最佳答案

如果您不介意覆盖对 200 的每个 204 响应,那么您可以使用过滤器:

import java.io.IOException;

import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.ext.Provider;

@Provider
public class NoContentToOkResposeFilter implements ContainerResponseFilter {

@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException {
if (responseContext.getStatus() == 204) {
responseContext.setStatus(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()));
}
}
}

最后用@ResponseStatus(200)注释你的资源方法:

@GET
@Path("/nothing")
@ResponseStatus(200)
public void nothing() {
}

关于rest - 返回 OK (200) 而不是 NO_CONTENT (204),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33415248/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com