Java 从JAX-RS服务获取资源时出错
我有一个简单的JAX-RS服务器应用程序:Java 从JAX-RS服务获取资源时出错,java,tomcat,jax-rs,Java,Tomcat,Jax Rs,我有一个简单的JAX-RS服务器应用程序: @GET @Path("/getImage/{key}") @Produces("image/jpeg") public final BufferedImage getImageResource(@PathParam("key") String key) { final File file = new File(key); // the key will be "cat.jpeg" e.t.c. final BufferedImage ima
@GET
@Path("/getImage/{key}")
@Produces("image/jpeg")
public final BufferedImage getImageResource(@PathParam("key") String key) {
final File file = new File(key); // the key will be "cat.jpeg" e.t.c.
final BufferedImage image = ImageIO.read(new FileInputStream(file));
return image;
}
将war文件部署到tomcat服务器(6.0)后,我将执行以下操作:
http://localhost:8080/resource-service/getImage/cat.png
问题:
1) 在新文件(键)上,它将转到tomcat根目录。我希望在类的项目目录中有类似于默认根文件夹的资源
2) 据我所知,不允许返回BuffereImage,我收到500条错误消息:
HTTP Status 500 - Could not find MessageBodyWriter for response object of type: java.awt.image.BufferedImage of media type: image/jpeg
如果您有任何建议,我将不胜感激。
提前谢谢 为了访问WAR软件包中的文件,您应该使用。首先,将其作为变量首先注入到类中:
@Context
ServletContext context;
然后使用以下命令查找文件:
final File file = new File(this.context.getRealPath(key));
无法返回缓冲图像
(并自动将其映射到图像/jpeg
),但在您的示例中,您不需要这样做。只需返回一个JAX-RS响应:
@GET
@Path("/getImage/{key}")
@Produces("image/jpeg")
public final Response get(@PathParam("key") String key) {
return Response.ok()
.entity(this.context.getResourceAsStream(key))
.type("image/jpeg")
.build();
}
类似问题:为了访问WAR软件包中的文件,您应该使用。首先,将其作为变量首先注入到类中:
@Context
ServletContext context;
然后使用以下命令查找文件:
final File file = new File(this.context.getRealPath(key));
无法返回缓冲图像
(并自动将其映射到图像/jpeg
),但在您的示例中,您不需要这样做。只需返回一个JAX-RS响应:
@GET
@Path("/getImage/{key}")
@Produces("image/jpeg")
public final Response get(@PathParam("key") String key) {
return Response.ok()
.entity(this.context.getResourceAsStream(key))
.type("image/jpeg")
.build();
}
类似的问题:您没有提到您的JAX-RS提供商,但在任何情况下,它们(afaik)都不提供能够直接序列化BuffereImage的MessageBodyWriter开箱即用。请参阅我的答案,以获取有关在序列化之前将缓冲图像转换为字节数组或输入流作为中间步骤的信息-。您没有提到JAX-RS提供商,但在任何情况下,它们(afaik)都不提供能够直接序列化缓冲图像的MessageBodyWriter开箱即用。请参阅我的答案,了解在序列化之前将缓冲图像转换为字节数组或输入流作为中间步骤的信息-。