Jersey - 在运行时设置REST响应编码

时间:2013-01-30 13:29:13

标签: java rest encoding jersey

我想知道是否可以使用Jersey API在运行时设置响应字符集。

如果我这样设置:

public class MyRESTClass
{
   private static final String encoding  = "UTF-8";

   @GET
   @Produces(MediaType.APPLICATION_JSON + ";charset=" + enconding)
   public String Call(@Context final HttpServletRequest servletReq, @QueryParam("somePar") String somePar)
   {
      ...
   }
}

......没关系

但如果我尝试这样设置:

public class MyRESTClass
{
   private static final String encoding  = getEncoding();

   public static final String getEncoding()
   {
      final String encoding = "UTF-8";
      return encoding;
   }

   @GET
   @Produces(MediaType.APPLICATION_JSON + ";charset=" + enconding)
   public String Call(@Context final HttpServletRequest servletReq, @QueryParam("somePar") String somePar)
   {
      ...
   }
}

我收到编译错误:

  

注释属性Produces.value的值必须是常量   表达

我需要这个,所以我可以使用配置文件设置应用程序的REST编码。

还有其他办法吗?

由于

2 个答案:

答案 0 :(得分:0)

我认为这样做的方法是扩展泽西岛的ResourceConfig并进行程序化资源配置。

String encoding = Config.get("encoding"); // get encoding from config file
String mediaType = MediaType.APPLICATION_JSON + ";charset=" + encoding;
final Resource.Builder getRes = Resource.builder().path("resourcePath");

final ResourceMethod.Builder get = getRes.addMethod("GET");
get.produces(mediaType).handledBy(new Inflector<ContainerRequestContext, String>() {
    public final String apply(ContainerRequestContext ctx) {
       // implement that Call method here
    }
});
registerResources(getRes.build());

然后,您应该通过为Jersey servlet设置initParameter来在web.xml中注册该自定义资源:

<filter>
    <filter-name>MyApplication</servlet-name>
    <filter-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
    <init-param>
        <param-name>javax.ws.rs.Application</param-name>
        <param-value>org.foo.MyApplication</param-value>
    </init-param>
<filter>

请参阅:https://jersey.java.net/documentation/latest/user-guide.html

答案 1 :(得分:-1)

Haven没有尝试过,但您可能会添加一个添加了特定编码的响应过滤器。

该类看起来像这样(手动键入,因此可能是错误):

public class ContentTypeEncodingFilter implements ContainerResponseFilter
{
  private static final String CONTENTTYPEHEADER = "Content-Type";
  private final String encoding;

  public ContentTypeEncodingFilter(final String encoding)
  {
    this.encoding = encoding;
  }

  @Override
  public ContainerResponse filter(final ContainerRequest request, final ContainerResponse response)
  {
    final MultivaluedMap<String, Object> headers = response.getHttpHeaders();
    final String type = (String)headers.getFirst(CONTENTTYPEHEADER);
    if (type != null)
    {
      headers.remove(CONTENTTYPEHEADER);
      headers.add(CONTENTTYPEHEADER, type + ";charset=" + this.encoding);
    }
    return response;
  }
}