so far, I'm returning html my home page by:
@GET
@Produces({MediaType.TEXT_HTML})
public String viewHome()
{
return "<html>...</html>";
}
what I want to do is return home.html itself and not copying its contents and returning the string instead.
How do I do this? thanks :)
If the URI path template variable cannot be cast to the specified type, the JAX-RS runtime returns an HTTP 400 (“Bad Request”) error to the client. If the @PathParam annotation cannot be cast to the specified type, the JAX-RS runtime returns an HTTP 404 (“Not Found”) error to the client.
JAX-RS is a specification defined by JSR-311 in the Java Community Process. Some of the key features provided by JAX-RS include: A collection of annotations for declaring resource classes and the data types they support. A set of interfaces that allow application developers to gain access to the runtime context.
In JAX-RS, we can use response. readEntity(String. class) to read the response body from a post request.
You can just return an instance of java.io.InputStream
or java.io.Reader
— JAX-RS will do the right thing.
@GET
@Produces({MediaType.TEXT_HTML})
public InputStream viewHome()
{
File f = getFileFromSomewhere();
return new FileInputStream(f);
}
getResourceAsStream
This is my preferred way of serving a web page using JAX-RS. The resources for the web page (html, css, images, js, etc.) are placed in main/java/resources
, which should deploy them in WEB-INF/classes
(may require some configuration depending on how you set up your project). Inject ServletContext
into your service and use it to find the file and return it as an InputStream
. I've included a full example below for reference.
@Path("/home")
public class HomeService {
@Context
ServletContext servletContext;
@Path("/{path: .+}")
@GET
public InputStream getFile(@PathParam("path") String path) {
try {
String base = servletContext.getRealPath("/WEB-INF/classes/files");
File f = new File(String.format("%s/%s", base, path));
return new FileInputStream(f);
} catch (FileNotFoundException e) {
// log the error?
return null;
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With