Whi*_*cal 5 java jetty jax-rs jersey jackson
我在Eclipse之外尝试运行Jetty Jersey和Jackson时变得疯狂.
我有一个主要课程:
public class Main {
public static void main(String[] args) throws Exception {
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.addServlet(org.glassfish.jersey.servlet.ServletContainer.class, "/*").setInitParameter(
"jersey.config.server.provider.classnames", CanaryEndpoint.class.getCanonicalName());
Server jettyServer = new org.eclipse.jetty.server.Server(8089);
jettyServer.setHandler(context);
jettyServer.start();
jettyServer.join();
}
}
Run Code Online (Sandbox Code Playgroud)
端点类:
@Path("/endpoint")
public class CanaryEndpoint {
@POST
@Path("/test")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public String canaryTest(ValueWrapper param) {
System.out.println("Deserialized Property: " + param.isFlag());
return "{OK}";
}
}
Run Code Online (Sandbox Code Playgroud)
和一个实体(反序列化)类:
@XmlRootElement
@XmlAccessorType(XmlAccessType.NONE)
public class ValueWrapper {
@XmlElement
public boolean flag;
public ValueWrapper() {}
public boolean isFlag() { return flag; }
public void setFlag(boolean flag) { this.flag = flag;}
}
Run Code Online (Sandbox Code Playgroud)
现在它来了有趣的部分.我使用Postman通过向8089端口发送POST请求来测试JSON消耗,并且{"flag" : "true"}使用Content-type和Accept充分设置的原始JSON值.
当我通过eclipse服务器正确播放Main类时,但是当我在CLI(mvn clean package + java -cpJar main_class)中执行它时,服务器应答错误415:Unsuported Media Type
我的简单pom.xml:
<jersey.version>2.14</jersey.version>
<jetty-version>9.2.6.v20141205</jetty-version>
(...)
<artifactId>jetty-server</artifactId>
<artifactId>jetty-servlet</artifactId>
<artifactId>jersey-container-servlet-core</artifactId>
<artifactId>jersey-json</artifactId>
<artifactId>jersey-media-json-jackson</artifactId>
Run Code Online (Sandbox Code Playgroud)
有关正在发生的事情的任何建议?
编辑:我缩小了一点问题.看起来像com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider在从控制台执行应用程序时没有注册.我该如何手动注册?
我不太确定从 IDE 运行和从命令行运行 jar 之间有什么区别,但我能够重现同样的问题。我尝试使用上面的代码以及这个答案中的代码
public class TestJerseyServer {
public static void main(String[] args) throws Exception {
ResourceConfig config = new ResourceConfig();
config.packages("jetty.practice.resources");
ServletHolder jerseyServlet
= new ServletHolder(new ServletContainer(config));
Server server = new Server(8080);
ServletContextHandler context
= new ServletContextHandler(server, "/");
context.addServlet(jerseyServlet, "/*");
server.start();
server.join();
}
}
Run Code Online (Sandbox Code Playgroud)
我能够让它工作的唯一方法是使用我的代码示例,但显式注册JacksonFeature
ResourceConfig config = new ResourceConfig();
config.register(JacksonFeature.class);
Run Code Online (Sandbox Code Playgroud)
我什至尝试设置一个 init-param 来扫描 Jackson 包,但这也不起作用。
| 归档时间: |
|
| 查看次数: |
1293 次 |
| 最近记录: |