Registering a provider programmatically in jersey which implements 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>
看看 Jersey 2 中的 ResourceConfig 类到底是什么? 了解有关不同部署模型的更多信息.有几种不同的方式来部署应用程序.您甚至可以混合搭配(web.xml 和 ResourceConfig).
Have a look at What exactly is the ResourceConfig class in Jersey 2? 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).
这篇关于在实现异常映射器的球衣中以编程方式注册提供程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在实现异常映射器的球衣中以编程方式注册提供程序
- C++ 和 Java 进程之间的共享内存 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
