仅支持有限数量的语言

时间:2016-04-26 17:00:56

标签: java jersey servlet-filters jersey-2.0 http-accept-language

我的API使用Jersey 2,现在我想支持国际化。我理解我的客户端应该指定Accept-Language参数,但我想了解如何正确处理它。

我们假设我的API应该只处理FRENCHENGLISH种语言。我知道我可以使用以下代码检索首选区域设置:

@GET
@Path("a-path")
public Response doSomething(@Context HttpServletRequest request) {
    Locale locale = request.getLocale();
    // ...
}

问题在于我的API不支持首选区域设置。让我们说我的客户根据w3c发送给我Accept-Language: da, en-gb;q=0.8, en;q=0.7,它基本上意味着:"I prefer Danish, but will accept British English and other types of English."。由于首选语言环境只返回最期望的语言环境,有没有办法通过我的API选择第一个支持的语言?我想在一个地方(即Filters)而不是每个资源处理它。

2 个答案:

答案 0 :(得分:3)

获取语言环境的一个方法是使用HttpHeaders#getAcceptableLanguages()

  

获取响应可接受的语言列表。

     

如果未指定可接受的语言,则返回包含单个通配符Locale实例的只读列表(语言字段设置为" *")。

     

<强>返回:       可读语言的只读列表,根据其q值排序,首先是最高优先级。

您可以使用HttpHeaders

在任何地方注入@Context
public Response doSomething(@Context HttpHeaders headers) {
    List<Locale> langs = headers.getAcceptableLanguages();

如果您想在filter中获取列表,还可以从ContainerRequestContext

获取区域设置列表
@Override
public void filter(ContainerRequestContext requestContext) throw .. {
    List<Locales> langs = requestContext.getAcceptableLanguages();
}

如果您想在资源方法中使用Locale,但又不想做所有语言环境&#34;解析&#34;在该方法中,您可以使用一些依赖注入,并创建一个Factory,您可以在其中注入HttpHeaders并解析那里的区域设置

另请参阅: Dependency injection with Jersey 2.0

下面是一个完整的测试用例示例,它使用了我提到的关于在Factory上使用过滤器和依赖项注入的最后两点的组合,以便您可以将已解析的Locale注入资源方法。该示例使用仅允许英语的虚拟区域设置解析程序。在我们解析了语言环境之后,我们将其设置为请求上下文属性,并从Factory内部进行检索,以便我们可以将其注入资源方法

@GET
public String get(@Context Locale locale) {
   return locale.toString();
}

另请参阅: How to inject an object into jersey request context?

如果您还有其他任何想要我解释的示例

,请告诉我
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import java.util.logging.Logger;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.container.PreMatching;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.Provider;

import org.glassfish.hk2.api.Factory;
import org.glassfish.hk2.utilities.binding.AbstractBinder;
import org.glassfish.jersey.filter.LoggingFilter;
import org.glassfish.jersey.process.internal.RequestScoped;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.test.JerseyTest;
import org.junit.Test;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;

/**
 * Stack Overflow question https://stackoverflow.com/q/36871274/2587435
 * 
 * Run this like any other JUnit test. Only one required test dependency:
 * 
 *  <dependency>
 *      <groupId>org.glassfish.jersey.test-framework.providers</groupId>
 *      <artifactId>jersey-test-framework-provider-inmemory</artifactId>
 *      <version>${jersey2.version}</version>
 *  </dependency>
 *
 * @author Paul Samsotha
 */
public class AcceptLanguageTest extends JerseyTest {

    @Path("language")
    public static class TestResource {

        @GET
        public String get(@Context Locale locale) {
           return locale.toString();
        }
    }

    public static interface LocaleResolver {
        Locale resolveLocale(List<Locale> locales);
    }

    // Note: if you look in the javadoc for getAcceptableLanguages()
    // you will notice that it says if there is not acceptable language
    // specified, that there is a default single wildcard (*) locale.
    // So this implementation sucks, as it doesn't check for that.
    // You will want to make sure to do so!
    public static class DefaultLocaleResolver implements LocaleResolver {

        @Override
        public Locale resolveLocale(List<Locale> locales) {
            if (locales.contains(Locale.ENGLISH)) {
                return Locale.ENGLISH;
            }
            return null;
        }
    }

    @Provider
    @PreMatching
    public static class LocaleResolverFilter implements ContainerRequestFilter {

        static final String LOCALE_PROPERTY = "LocaleResolverFilter.localProperty";

        @Inject
        private LocaleResolver localeResolver;

        @Override
        public void filter(ContainerRequestContext context) throws IOException {
            List<Locale> locales = context.getAcceptableLanguages();
            Locale locale = localeResolver.resolveLocale(locales);
            if (locale == null) {
                context.abortWith(Response.status(Response.Status.NOT_ACCEPTABLE).build());
                return;
            }
            context.setProperty(LOCALE_PROPERTY, locale);
        }
    }

    public static class LocaleFactory implements Factory<Locale> {

        @Context
        private ContainerRequestContext context;

        @Override
        public Locale provide() {
            return (Locale) context.getProperty(LocaleResolverFilter.LOCALE_PROPERTY);
        }

        @Override
        public void dispose(Locale l) {} 
    }

    @Override
    public ResourceConfig configure() {
        return new ResourceConfig(TestResource.class)
                .register(LocaleResolverFilter.class)
                .register(new AbstractBinder() {
                    @Override
                    protected void configure() {
                        bindFactory(LocaleFactory.class)
                                .to(Locale.class).in(RequestScoped.class);
                        bind(DefaultLocaleResolver.class)
                                .to(LocaleResolver.class).in(Singleton.class);
                    }
                })
                .register(new LoggingFilter(Logger.getAnonymousLogger(), true));
    }

    @Test
    public void shouldReturnEnglish() {
        final String accept = "da, en-gb;q=0.8, en;q=0.7";
        final Response response = target("language").request()
                .acceptLanguage(accept)
                .get();
        assertThat(response.readEntity(String.class), is("en"));
    }

    @Test
    public void shouldReturnNotAcceptable() {
        final String accept = "da";
        final Response response = target("language").request()
                .acceptLanguage(accept)
                .get();
        assertThat(response.getStatus(), is(Response.Status.NOT_ACCEPTABLE.getStatusCode()));
    }
}

答案 1 :(得分:0)

JAX-RS API允许您使用Request.selectVariant(List)方法选择语言环境。

在REST处理程序或CDI bean中尝试以下代码:

import javax.ws.rs.core.Variant;
import javax.ws.rs.core.Request;

    @Context
    private Request req;

    private Locale getResponseLocale(boolean throwIfNoneMatch) throws NotAcceptableException{
        // Put your supported languages here
        List<Variant> langVariants = Variant.languages(
                new Locale("da"), 
                new Locale("en-gb"), 
                Locale.getDefault()).build();

        Locale locale = Locale.getDefault();
        Variant selectVariant = this.req.selectVariant(langVariants);
        if (selectVariant != null) {
            locale = selectVariant.getLanguage();
        } else if (throwIfNoneMatch) {
            throw new NotAcceptableException(Response.notAcceptable(langVariants).build());
        }

        return locale;
    }

另请参阅The Java EE Tutorial : Runtime Content Negotiation