Generate an HTML Response in a Java Servlet
Asked Answered
D

3

55

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

Dionnedionysia answered 3/3, 2010 at 12:2 Comment(0)
Q
111

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 keeps JSP code free from Scriptlet clutter and this 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.

Quickie answered 3/3, 2010 at 13:36 Comment(4)
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.Bottomless
@Timo: either you misunderstood your architect, or your architect needs to read #3178233, #2095897 and stackoverflow.com/tags/servlets/info If still not convinced, fire yourself and look for another project.Quickie
I had to remove /WEB-INF/ in the string to make it work. +1Wendy
@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?Quickie
F
35

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

Fructificative answered 3/3, 2010 at 12:6 Comment(5)
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.Fancie
Or use some framework/tools like dojo, GWT etc. and keep client side html completely separate from server side code.Woolfell
@duffymo: But sometimes, in certain occasion, I'd like to generate on-going progress html response from Servlet. Not everying is suitable for MVC.Authorship
@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.Authorship
"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.Fancie
D
1

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();
}
Dormancy answered 15/3, 2020 at 1:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.