简体   繁体   中英

Java & Jersey 1.17: Custom default response headers

I am currently using Java and Jersey 1.17 to create a web service. However, in all the response headers, I always get the current version of whatever web container I am using, such as

Content-Type -> application/json
Server -> Jetty(8.1.10.v20130312)
Transfer-Encoding -> chunked

is there any way in Jersey to remove the "Server" key-value from the response headers by default, without having to create the Response, remove it manually and then return it?

Any help is much appreciated!

I don't think jersey provides this feature but you can achieve this by writing a Servlet Response Filter.

Learn more about servlet filters here: http://punekaramit.wordpress.com/2010/03/16/intercepting-http-response-using-servlet-filter/

Or read the Oracle docs: http://www.oracle.com/technetwork/java/filters-137243.html

Here is tutorial how to use filtering requests and responses in java. The Java EE 5 Tutorial

You can use HttpServletResponse.setHeader(java.lang.String name, java.lang.String value) to set any header you want.

Regards, Evgeniy

Creating such a filter is pretty easy:

public class ServerHeaderFilter implements ContainerResponseFilter
{
  private static final String SERVERHEADER = "Server";

  @Override
  public ContainerResponse filter(final ContainerRequest request, final ContainerResponse response)
  {
    response.getHttpHeaders().remove(SERVERHEADER);
    return response;
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM