在jersey中以编程方式注册实现Exceptionmapper的提供程序 [英] Registering a provider programmatically in jersey which implements exceptionmapper

查看:58
本文介绍了在jersey中以编程方式注册实现Exceptionmapper的提供程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在实现由jersey API提供的Exceptionmapper的jersey中以编程方式注册我的提供程序?我不想使用@Provider批注,也不想使用ResourceConfig注册提供程序,该怎么办?

How do I register my provider programmatically in jersey which implements the Exceptionmapper provided by jersey API? I don't want to use @Provider annotation and want to register the provider using ResourceConfig, how can I do that?

例如:

public class MyProvider implements ExceptionMapper<WebApplicationException> extends ResourceConfig {

     public MyProvider() {
        final Resource.Builder resourceBuilder = Resource.builder();
        resourceBuilder.path("helloworld");

        final ResourceMethod.Builder methodBuilder = resourceBuilder.addMethod("GET");
        methodBuilder.produces(MediaType.TEXT_PLAIN_TYPE)
                .handledBy(new Inflector<ContainerRequestContext, String>() {

            @Override
            public String apply(ContainerRequestContext containerRequestContext) {
                return "Hello World!";
            }
        });

        final Resource resource = resourceBuilder.build();
        registerResources(resource);
    }

    @Override
    public Response toResponse(WebApplicationException ex) {
        String trace = Exceptions.getStackTraceAsString(ex);
        return Response.status(500).entity(trace).type("text/plain").build();
    }
}

这是正确的方法吗?

推荐答案

我猜您没有ResourceConfig,因为您似乎不确定如何使用它.首先,它不是必需的.如果您使用使用它,那应该是它自己的单独类.您可以在其中注册映射器.

I'm guessing you don't have a ResourceConfig, since you seem to not be sure how to use it. For one, it is not required. If you do use it, it should be it's own separate class. There you can register the mapper.

public class AppConfig extends ResourceConfig {
    public AppConfig() {
        register(new MyProvider());
    }
}

但是您可能正在使用web.xml.在这种情况下,您可以使用以下<init-param>

But you are probably using a web.xml. In which case, you can register the provider, with the following <init-param>

<servlet>
    <servlet-name>MyApplication</servlet-name>
    <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
    <init-param>
        <param-name>jersey.config.server.provider.classnames</param-name>
        <param-value>
            org.foo.providers.MyProvider
        </param-value>
    </init-param>
</servlet>

请参阅应用程序部署和运行时环境,以获取更多信息不同的部署模型.有几种不同的方法来部署应用程序.您甚至可以混合和匹配(web.xml和ResourceConfig).

Have a look at Application Deployment and Runtime Environments for more information on different deployment models. There are a few different ways to deploy applications. You can even mix and match (web.xml and ResourceConfig).

这篇关于在jersey中以编程方式注册实现Exceptionmapper的提供程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆