I have simple JAX-RS server application:
@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;
}
After deploying war file to tomcat server (6.0), i do next:
http://localhost:8080/resource-service/getImage/cat.png
Problems:
1)On new File(key) it’ll go to tomcat root directory. I’d like to have something like default root folder for resources inside project directory around classes.
2)Returning BufferedImage doesn’t allowed as i understand, i get 500 error message:
HTTP Status 500 - Could not find MessageBodyWriter for response object of type: java.awt.image.BufferedImage of media type: image/jpeg
I’d appreciate any advice, links.
Thanks in advance!
In order to get access to the files in your WAR package you should use
ServletContext. First, inject it first into your class as a variable:and then find files using:
It’s not possible to return a
BufferedImage(and map it automatically toimage/jpeg), but in your example you don’t need to do it. Just return a JAX-RS response:Similar question: Dynamically create image from JAX-RS servlet