22

This works to return a string:

import javax.servlet.http.*;
@SuppressWarnings("serial")
public class MonkeyServlet extends HttpServlet {
    public void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws IOException {

        resp.setContentType("text/plain");
        resp.getWriter().println("got this far");

    }

}

But I can't get it to return an html document. This doesn't work:

import javax.servlet.http.*;
@SuppressWarnings("serial")
public class BlotServlet extends HttpServlet {
    public void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws IOException {

        resp.setContentType("text/html");
        resp.getWriter().println("html/mypage.html");

    }

}

Sorry for being noob!

EDIT:

I already have the html in separate documents. So I need to either return the document, or read/parse it somehow, so I'm not just retyping all the html...

EDIT:

I have this in my web.xml

<servlet> 
    <servlet-name>Monkey</servlet-name> 
    <servlet-class>com.self.edu.MonkeyServlet</servlet-class> 
</servlet> 
<servlet-mapping> 
    <servlet-name>Monkey</servlet-name> 
    <url-pattern>/monkey</url-pattern> 
</servlet-mapping>

Is there something else I can put in there so it just returns a file, like...

<servlet-mapping> 
    <servlet-name>Monkey</servlet-name> 
    <file-to-return>blot.html</file-to-return> 
</servlet-mapping>
monkey blot
  • 985
  • 3
  • 10
  • 18

1 Answers1

56

You either print out the HTML from the Servlet itself (deprecated)

PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<h1>My HTML Body</h1>");
out.println("</body></html>");

or, dispatch to an existing resource (servlet, jsp etc.) (called forwarding to a view) (preferred)

RequestDispatcher view = request.getRequestDispatcher("html/mypage.html");
view.forward(request, response);

The existing resource that you need your current HTTP request to get forwarded to does not need to be special in any way i.e. it's written just like any other Servlet or JSP; the container handles the forwarding part seamlessly.

Just make sure you provide the correct path to the resource. For example, for a servlet the RequestDispatcher would need the correct URL pattern (as specified in your web.xml)

RequestDispatcher view = request.getRequestDispatcher("/url/pattern/of/servlet");

Also, note that the a RequestDispatcher can be retrieved from both ServletRequest and ServletContext with the difference that the former can take a relative path as well.

Reference:
http://docs.oracle.com/javaee/5/api/javax/servlet/RequestDispatcher.html

Sample Code

public class BlotServlet extends HttpServlet {
    public void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws IOException {
        // we do not set content type, headers, cookies etc.
        // resp.setContentType("text/html"); // while redirecting as
        // it would most likely result in an IllegalStateException

        // "/" is relative to the context root (your web-app name)
        RequestDispatcher view = req.getRequestDispatcher("/path/to/file.html");
        // don't add your web-app name to the path

        view.forward(req, resp);    
    }

}
emecas
  • 1,586
  • 3
  • 27
  • 43
Ravi K Thapliyal
  • 51,095
  • 9
  • 76
  • 89
  • can you show what the "existing servlet" you mentioned would look like? – monkey blot Jun 11 '13 at 03:46
  • The code blocks in my answer would go in your existing servlet: the one handling the HTTP request. The resource being dispatched to be it a servlet or jsp or html does not need to implement any special interface. So, the existing servlet used for getting dispatched to would be like any other normal servlet. – Ravi K Thapliyal Jun 11 '13 at 03:48
  • a servlet means code like in my question, right? So you're saying my current servlet should just call another servlet? But what is the code in the final servlet which returns an html file rather than String? – monkey blot Jun 11 '13 at 04:07
  • I'm afraid I may have overcomplicated my question.... My situation is, I have an html document. I'm just trying to make it so when whatever url is requested, the document is sent over and loaded in the client's browser. I think I'm almost there with my servlet so far, just need to tweak 1 or 2 lines of code from my question above. Right? – monkey blot Jun 11 '13 at 04:16
  • 1
    (1) Yes, by servlet I mean code like in your question. No, your current servlet should just dispatch directly to that html file. (2) You need to have a catch all (/*) URL pattern configured for your servlet in web.xml. Then this servlet could simply forward to (or include) your html file. – Ravi K Thapliyal Jun 11 '13 at 04:24
  • So I specify the file to return in web.xml? Can you show what that looks like? – monkey blot Jun 11 '13 at 04:27
  • No, you just specify the Servlet in web.xml (like you've done). Your Monkey servlet should then dispatch to the html file internally i.e. the address bar URL won't change but you'll still see your html file contents. Try with my sample code. I'll help you out with any errors you may face. Just get your path correct and you'll be fine. – Ravi K Thapliyal Jun 11 '13 at 04:40
  • ok, finally got it. Thanks for sticking with it! – monkey blot Jun 11 '13 at 05:27
  • 1
    For some reason it only works if the file name and dispatcher code both have .jsp, but .html doesn't work... Any, thats ok. I can change all my html docs to .jsp – monkey blot Jun 11 '13 at 05:34
  • 1
    I'm glad you got it working but dispatch works for both dynamic (servlet, jsps) as well as static (html) resources. You may have to tinker with the path specified a bit. – Ravi K Thapliyal Jun 11 '13 at 05:41
  • @Ravi Thapliyal Thank for the answer, but how do I dynamically parse in variable into the html context ? By doing printwriter I can String htmlRespone = ""; htmlRespone += "

    Your username is: " + username + "
    "; where by the variable is being sent . It is possible to send variable info from RequestDispatcher ?

    – newbieprogrammer May 12 '16 at 11:18