52

How do I generate an HTML response in a Java servlet?

BalusC
  • 992,635
  • 352
  • 3,478
  • 3,452
ogechi nwogu
  • 529
  • 1
  • 5
  • 3

3 Answers3

107

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. You can put JSP files in /WEB-INF folder to prevent users from directly accessing them without invoking the preprocessing servlet.

Kickoff example:

@WebServlet("/hello")
public class HelloWorldServlet extends HttpServlet {

    @Override
    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/hello.jsp").forward(request, response);
    }

}

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

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

When opening http://localhost:8080/contextpath/hello this will show

Message: Hello World

in the browser.

This keeps the Java code free from HTML clutter and greatly improves maintainability. To learn and practice more with servlets, continue with below links.

Also browse the "Frequent" tab of all questions tagged [servlets] to find frequently asked questions.

BalusC
  • 992,635
  • 352
  • 3,478
  • 3,452
  • 2
    Is this still a valid approach? I always hear our lead architect saying not to use JSP at all but then I ask myself how should I create all the HTML? Create each element one by one programatically? That probably takes forever. – Timo Ernst Aug 04 '14 at 08:24
  • 3
    @Timo: either you misunderstood your architect, or your architect needs to read http://stackoverflow.com/questions/3177733/how-to-avoid-java-code-in-jsp-files, http://stackoverflow.com/questions/2095397/what-is-the-difference-between-jsf-servlet-and-jsp and http://stackoverflow.com/tags/servlets/info If still not convinced, fire yourself and look for another project. – BalusC Aug 04 '14 at 08:26
  • I had to remove /WEB-INF/ in the string to make it work. +1 – Björn Hallström Jun 18 '17 at 07:01
  • 1
    @BjörnHallström: That can happen if you haven't actually placed the JSP in /WEB-INF folder as instructed in the example. This way the enduser will be able to open the JSP directly without invoking the servlet by simply entering JSP's URL in browser's address bar. Is that what you want to allow? – BalusC Jun 18 '17 at 13:36
34

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
  • 410,890
  • 80
  • 476
  • 515
  • 15
    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 Mar 03 '10 at 12:11
  • 2
    Or use some framework/tools like dojo, GWT etc. and keep client side html completely separate from server side code. – saugata Mar 03 '10 at 12:40
  • 2
    @duffymo: But sometimes, in certain occasion, I'd like to generate on-going progress html response from Servlet. Not everying is suitable for MVC. – Scott Chu Sep 28 '17 at 04:07
  • @duffymo: I do have an actual case. I have an old servlet that counts each of many data sources of their amount up to current day. It runs using wget. so in order to let wget catches its output. I need to generate html directly.(note: This is an old program, nobody will rewrite it with too much effort. – Scott Chu Sep 29 '17 at 07:04
  • "old program" - exactly. People used to write JSPs with scriptlets in them, but nobody in their right mind would continue to do so once they learned how unreadable and unmaintainable they are. – duffymo Sep 29 '17 at 10:00
0

Apart of directly writing HTML on the PrintWriter obtained from the response (which is the standard way of outputting HTML from a Servlet), you can also include an HTML fragment contained in an external file by using a RequestDispatcher:

public void doGet(HttpServletRequest request,
       HttpServletResponse response)
       throws IOException, ServletException {
   response.setContentType("text/html");
   PrintWriter out = response.getWriter();
   out.println("HTML from an external file:");     
   request.getRequestDispatcher("/pathToFile/fragment.html")
          .include(request, response); 
   out.close();
}
Marco
  • 353
  • 4
  • 6