Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return actual html file using JAX-RS

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 :)

like image 469
Rey Libutan Avatar asked Jul 15 '12 06:07

Rey Libutan


People also ask

What can a JAX-RS method return?

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.

What is JAX-RS used for?

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.

How do you request a body in Jax Runescape?

In JAX-RS, we can use response. readEntity(String. class) to read the response body from a post request.


3 Answers

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);
}
like image 142
Sean Reilly Avatar answered Oct 15 '22 02:10

Sean Reilly


  1. Read the File using getResourceAsStream
  2. write back to returned String.
like image 37
Puspendu Banerjee Avatar answered Oct 15 '22 01:10

Puspendu Banerjee


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;
        }
    }
}
like image 1
Robin Keskisarkka Avatar answered Oct 15 '22 03:10

Robin Keskisarkka