泽西岛:如何将杰克逊添加到Servlet Holder [英] Jersey: How to Add Jackson to Servlet Holder

查看:154
本文介绍了泽西岛:如何将杰克逊添加到Servlet Holder的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Jersey创建一个嵌入式Jetty webapp。我不知道如何在这里添加杰克逊自动JSON serde:

I am creating an embedded Jetty webapp with Jersey. I do not know how to add Jackson for automatic JSON serde here:

    ServletHolder jerseyServlet = context.addServlet(
       org.glassfish.jersey.servlet.ServletContainer.class, "/*");
    jerseyServlet.setInitOrder(0);

    jerseyServlet.setInitParameter(
        ServerProperties.PROVIDER_CLASSNAMES,
        StringUtils.join(
            Arrays.asList(
                HealthCheck.class.getCanonicalName(),
                Rest.class.getCanonicalName()),
            ";"));

    // Create JAX-RS application.
    final Application application = new ResourceConfig()
        .packages("com.example.application")
        .register(JacksonFeature.class);

    // what do I do now to tie this to the ServletHolder?

如何使用以下方式注册 ResourceConfig ServletHolder所以在使用注释 @Produces(MediaType.APPLICATION_JSON)的地方使用?以下是嵌入式Jetty应用程序的完整主类

How do I register this ResourceConfig with the ServletHolder so Jackson with be used where the annotation @Produces(MediaType.APPLICATION_JSON) is used? Here is the full main class for the embedded Jetty application

package com.example.application.web;

import com.example.application.api.HealthCheck;
import com.example.application.api.Rest;
import com.example.application.api.Frontend;
import org.apache.commons.lang.StringUtils;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.glassfish.jersey.jackson.JacksonFeature;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.server.ServerProperties;

import javax.ws.rs.core.Application;
import java.util.Arrays;

public class JettyStarter {

public static void main(String[] args) throws Exception {

    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
    context.setContextPath("/");
    Server jettyServer = new Server(9090);
    jettyServer.setHandler(context);
    ServletHolder jerseyServlet = context.addServlet(
     org.glassfish.jersey.servlet.ServletContainer.class, "/*");
    jerseyServlet.setInitOrder(0);

    jerseyServlet.setInitParameter(
        ServerProperties.PROVIDER_CLASSNAMES,
        StringUtils.join(
            Arrays.asList(
                HealthCheck.class.getCanonicalName(),
                Rest.class.getCanonicalName()),
            ";"));

    // Create JAX-RS application.
    final Application application = new ResourceConfig()
        .packages("com.example.application")
        .register(JacksonFeature.class);


    try {
        jettyServer.start();
        jettyServer.join();
    } catch (Exception e) {
        System.out.println("Could not start server");
        e.printStackTrace();
    } finally {
        jettyServer.destroy();
    }
}
}


推荐答案

一种方法是将 ResourceConfig 包装在显式构造。 java.net/apidocs/2.8/jersey/org/glassfish/jersey/servlet/ServletContainer.htmlrel =nofollow noreferrer> ServletContainer ,见过此处

One way is to just wrap the ResourceConfig in an explicit construction of the ServletContainer, as seen here.

使用您的示例进行测试

public class RestServer {

    public static void main(String[] args) throws Exception {

        // Create JAX-RS application.
        final ResourceConfig application = new ResourceConfig()
                .packages("jersey.jetty.embedded")
                .register(JacksonFeature.class);

        ServletContextHandler context 
                 = new ServletContextHandler(ServletContextHandler.SESSIONS);
        context.setContextPath("/");
        Server jettyServer = new Server(9090);
        jettyServer.setHandler(context);
        ServletHolder jerseyServlet = new ServletHolder(new
                org.glassfish.jersey.servlet.ServletContainer(application));
        jerseyServlet.setInitOrder(0);

        context.addServlet(jerseyServlet, "/*");

        // ... removed property (init-param) to compile. 

        try {
            jettyServer.start();
            jettyServer.join();
        } catch (Exception e) {
            System.out.println("Could not start server");
            e.printStackTrace();
        } finally {
            jettyServer.destroy();
        }
    }
}



你也可以...



而不更改原始帖子中的任何其他内容,只需将init参数设置为扫描杰克逊提供程序包

You could also...

without changing anything else in your original post, just set the init param to scan the Jackson provider package

jerseyServlet.setInitParameter(ServerProperties.PROVIDER_PACKAGES,
        "com.fasterxml.jackson.jaxrs.json;"
      + "jersey.jetty.embedded"  // my package(s)
);

注意您尝试使用 ResourceConfig 似乎是因为您已经在init参数中配置了类,所以很少冗余。你也可以明确地删除每个类,并像我一样扫描整个包。

Note your attempted use of ResourceConfig seems a little redundant, as you are already configuring your classes in the the init param. You could alternatively get rid of adding each class explicitly and just scan entire packages as I have done.

只需使用您需要的Jackson提供程序类。您可以查看jar,您将看到的不仅仅是编组/解组提供程序(Jackson [JAXB] JsonProvider),就像ExceptionMappers一样。您可能不喜欢这些映射器和魔杖配置您自己的。在这种情况下,就像我说的那样,只需要包含您需要的提供程序。例如

just use the Jackson provider classes you need. You can look in the jar, and you will see more than just the marshalling/unmarhalling provider (Jackson[JAXB]JsonProvider), like a ExceptionMappers. You may not like these mappers and wand to configure your own. In which case, like I said, just include the provider you need. For example

jerseyServlet.setInitParameter(ServerProperties.PROVIDER_CLASSNAMES,
      "com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider");

jerseyServlet.setInitParameter(ServerProperties.PROVIDER_PACKAGES, 
      "jersey.jetty.embedded"  // my package(s)
);



经过进一步测试......



不确定是什么版本的泽西岛,但我使用的是泽西岛2.15(带有 jersey-media-json-jackson:2.15 ),而且没有任何进一步的只需扫描 my 包中的资源类配置,Jackson功能已经启用。这是自动发现功能的一部分。我相信这是杰克逊功能的2.8或2.9。因此,如果您使用的是后者,我认为您不需要明确配置任何内容,至少从我测试的内容开始: - )

After further testing...

Not sure what version of Jersey, but I am using Jersey 2.15 (with jersey-media-json-jackson:2.15), and without any further configuration from just scanning my package for my resource classes, the Jackson feature is already enabled. This is part of the auto discoverable features. I believe this was enable as of 2.8 or 2.9 for the Jackson feature. So if you are using a later one, I don't think you need to explicitly configure anything, at least from what I've tested :-)

所有上述示例均已使用以下Maven pom.xml进行测试

All of the above examples have been tested with the below Maven pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
                xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
                http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.underdog.jersey</groupId>
    <artifactId>jersey-jetty-embedded</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.7</maven.compiler.source>
        <maven.compiler.target>1.7</maven.compiler.target>
        <jersey.version>2.15</jersey.version>
        <jetty.version>9.2.6.v20141205</jetty.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-servlet</artifactId>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.media</groupId>
            <artifactId>jersey-media-json-jackson</artifactId>
        </dependency>
        <dependency>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-server</artifactId>
            <version>${jetty.version}</version>
        </dependency>
        <dependency>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-servlet</artifactId>
            <version>${jetty.version}</version>
        </dependency>
        <dependency>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-servlets</artifactId>
            <version>${jetty.version}</version>
        </dependency>
    </dependencies>

        <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.glassfish.jersey</groupId>
                <artifactId>jersey-bom</artifactId>
                <version>${jersey.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
</project>

资源等级

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

@Path("/json")
public class JsonResource {

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Response getJson() {
        Resource resource = new Resource();
        resource.hello = "world";
        return Response.ok(resource).build();
    }

    public static class Resource {
        public String hello;
    }
}

使用路径


http:// localhost:9090 / json

这篇关于泽西岛:如何将杰克逊添加到Servlet Holder的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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