1

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 エンコーディングを設定できるようにするために必要です。

別の方法はありますか?

ありがとう

4

1 に答える 1

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());

web.xml次に、Jersey サーブレットの initParameter を設定して、そのカスタム リソースを登録する必要があります。

<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

于 2014-02-14T09:31:56.093 に答える