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 :)
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;
}
}
}
您可以使用HtmlEasy这是建立在RestEasy的,这是一个非常好的实现JAX-RS的顶部。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.