如何在Spring Boot中根据响应载荷的值添加HTTP响应头

huangapple go评论84阅读模式
英文:

How to add HTTP Response Header by a value of Response Payload in Spring Boot

问题

我想在我的Spring Boot项目中,在Response生成之后,通过filter或类似的方式设置HttpServletResponse的头部。在过滤器中,我可以进行类似以下的操作:

 ((HttpServletResponse)servletResponse).addHeader("test","value");
  fc.doFilter(request, servletResponse);

但问题是,我的头部值是根据响应体(payload)本身生成的,因此我必须使用ServletResponse负载的内容将其添加到头部。我该如何实现?

我可以在控制器级别上实现它,但我不想为所有的响应手动执行此操作。

英文:

I want to set the header of HttpServletResponse in filter or something similar after the Response is generated in my spring boot project. In filter, I can do something similar:

 ((HttpServletResponse)servletResponse).addHeader("test","value");
  fc.doFilter(request, servletResponse);

But the problem is that my header value is generated from the response body(payload) itself, so I have to use the content of ServletResponse payload to add it to the header. How can I do it?

I could do it on controller level but I don't want to do it manually for all the responses.

答案1

得分: 1

我在过滤器中实现了ContentCachingResponseWrapper,以获取响应主体并从ServletResponse中添加头,如下所示:

@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

    ContentCachingResponseWrapper responseCacheWrapperObject = new ContentCachingResponseWrapper((HttpServletResponse) servletResponse);
    filterChain.doFilter(servletRequest, responseCacheWrapperObject);

    byte[] responseArray = responseCacheWrapperObject.getContentAsByteArray();
    String responseStr = new String(responseArray, responseCacheWrapperObject.getCharacterEncoding());
    
   //这是我自己的逻辑函数,从responseStr生成头部值
   String headerValue = getHeaderValueFromResponseString(responseStr);
      
   responseCacheWrapperObject.addHeader("headerKey", headerValue)

    responseCacheWrapperObject.copyBodyToResponse();
}
英文:

I implemented the ContentCachingResponseWrapper in the Filter to get the response body and to add the header from ServletResponse as follow:

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        ContentCachingResponseWrapper responseCacheWrapperObject = new ContentCachingResponseWrapper((HttpServletResponse) servletResponse);
        filterChain.doFilter(servletRequest, responseCacheWrapperObject);

        byte[] responseArray = responseCacheWrapperObject.getContentAsByteArray();
        String responseStr = new String(responseArray, responseCacheWrapperObject.getCharacterEncoding());
        
       //This is my own logic function to generate header value from responseStr
       String headerValue = getHeaderValueFromResponseString(responseStr);
          
       responseCacheWrapperObject.addHeader("headerKey", headerValue)

        responseCacheWrapperObject.copyBodyToResponse();
    }

答案2

得分: 0

你可以使用这段代码:

String authorizationHeader = request.getHeader("Authorization");
if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
    token = authorizationHeader.substring(7);
    userName = jwtUtil.extractUsername(token);
    request.setAttribute("userid", userName);
}

所以现在这段代码生成一个令牌,其中包括用户名(userName)以及令牌本身。

英文:

You can make use of this code

 String authorizationHeader = request.getHeader("Authorization");
        if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
            token = authorizationHeader.substring(7);
            userName = jwtUtil.extractUsername(token);
            request.setAttribute("userid",userName);
        }

so now this code generates a token where you have userid that gives userName along with the token

huangapple
  • 本文由 发表于 2020年9月18日 10:35:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/63948558.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定