views:

142

answers:

2

how to generate HTML response in a servlet

+3  A: 

You need to have a doGet method as:

public void doGet(HttpServletRequest request,
        HttpServletResponse response)
throws IOException, ServletException
{
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    out.println("<html>");
    out.println("<head>");
    out.println("<title>Hola</title>");
    out.println("</head>");
    out.println("<body bgcolor=\"white\">");
    out.println("</body>");
    out.println("</html>");
}

You can see this link for a simple hello world servlet

codaddict
It's not recommended to generate HTML from a servlet this way. That's a 1998 vintage idiom. A better solution would be to use a JSP.
duffymo
Or use some framework/tools like dojo, GWT etc. and keep client side html completely separate from server side code.
saugata
+8  A: 

You normally forward the request to a JSP for display. JSP is a view technology which provides a template to write plain vanilla HTML/CSS/JS in and provides ability to interact with backend Java code/variables with help of taglibs and EL. You can control the page flow with taglibs like JSTL. You can set any backend data as an attribute in any of the request, session or application scope and use EL (the ${} things) in JSP to access/display them.

Kickoff example:

public class HelloWorldServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String message = "Hello World";
        request.setAttribute("message", message); // This will be available as ${message}
        request.getRequestDispatcher("/WEB-INF/page.jsp").forward(request, response);
    }
}

And /WEB-INF/page.jsp look like:

<!doctype html>
<html lang="en">
    <head>
        <title>SO question 2370960</title>
    </head>
    <body>
         <p>Message: ${message}</p>
    </body>
</html>

this will show

Message: Hello World

in the browser.

This keeps the Java code free from HTML clutter and greatly improves maintainability. To learn more about EL (and taglibs), check this and this chapter of the Java EE tutorial.

BalusC
+1, good explanation.
Zaki
+1 - very good, as usual.
duffymo