java—在SpringBoot中是否有任何选项可以向所有@requestheaders添加默认值?

bweufnob  于 2021-07-06  发布在  Java
关注(0)|答案(2)|浏览(586)

是否有任何选项可以将默认值添加到所有 @RequestHeader 你穿的是春靴吗? @RequestHeader(value = "User-Accept-Language", defaultValue = "en-IN") String localeCd 我正在复制/粘贴所有api。任何帮助,以避免代码重复!!

hmtdttj4

hmtdttj41#

我没有找到任何已经做了有一个添加值的标题注解,所以我自己做了。下面是代码,很简单,我用SpringAOP做的
我创建了注解类

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface ResponseHeader {

    public String key() default "";

    public String value() default "";
}

以及一个包含标题和注解的数组

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface ResponseHeaders {

    public ResponseHeader[] headers();
}

用于捕捉restcontrollers的aop类(您可以自定义aop,以便根据需要设置自己的切入点:

import YOUR_PACKAGE_ANNOTATION.ResponseHeaders;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * Aspect for inserting headers on the methods of the @RestController         
 annotated classes
 */
 @Aspect
 @Component
 public class ResponseHeadersAnnotation {

 /**
 * Pointcut for filtering just classes with @RestController annotation
 */
@Pointcut("@within(org.springframework.web.bind.annotation.RestController)")
public void restControllerClass() {
}

/**
 * It adds the headers to the response of the method of the controller
 *
 * @param responseHeaders
 */
@After("restControllerClass() && @annotation(responseHeaders)")
public void addHeaders(final ResponseHeaders responseHeaders) {
    final HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
    List.of(responseHeaders.headers()).forEach(responseHeader -> response.setHeader(responseHeader.key(), responseHeader.value()));
 }
}

下面是如何在控制器中使用它的示例:

@GetMapping(value = {"/ServiceTicketCollection", "/ServiceRequestCollection"})
@ResponseHeaders(headers = {
        @ResponseHeader(key = "cookie1", value = "value1"),
        @ResponseHeader(key = "cookie2, value = "value2")
})
public Object restControllerMethod() {
    ...
}
zpqajqem

zpqajqem2#

这是一个关于如何使用springwebflux为头提供默认值的示例

@Component
public class CorrelationIdFilter implements WebFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        var correlationId = exchange.getRequest().getHeaders().getFirst(CORRELATION_ID_HEADER);
        if (correlationId == null || correlationId.isEmpty()) {
            correlationId = UUID.randomUUID().toString();
            ServerHttpRequest mutatedRequest = exchange.getRequest()
                    .mutate()
                    .header(CORRELATION_ID_HEADER, correlationId)
                    .build();
            exchange = exchange
                    .mutate()
                    .request(mutatedRequest)
                    .build();
        }
        exchange.getResponse().getHeaders().add(CORRELATION_ID_HEADER, correlationId);
        return chain.filter(exchange);
    }
}

这是给SpringWeb的

@Component
public class CorrelationIdFilter implements Filter {

    static final String CORRELATION_ID_HEADER = "X-Correlation-ID";

    @Override
    public void init(FilterConfig filterConfig) {
        // empty
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        HttpServletRequest httpRequest = (HttpServletRequest) request;
        String correlationId = httpRequest.getHeader(CORRELATION_ID_HEADER);
        if (correlationId == null) {
           correlationId = XidFactory.nextXid();
           ((HttpServletResponse) response).addHeader(CORRELATION_ID_HEADER, correlationId);
        }

        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        // empty
    }
}

相关问题