Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What HTML templating options are there in Java as an alternative to doing HTML output from your servlet code?

Given the following Hello World servlet, how could you transfer the Hello World output out of the servlet code and put it in some kind of HTML templating format? I would like to simply call the template from the servlet and have it render the Java variables I refer to in the template - perhaps by referring to the "Hello World" string as a class variable in the SprogzServlet class?

package boochy;

import java.io.IOException;
import javax.servlet.http.*;

@SuppressWarnings("serial")
public class SprogzServlet extends HttpServlet
{
    public void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws IOException
    {
        resp.setContentType("text/plain");
        resp.getWriter().println("Hello, world");
    }
}
like image 948
Yen Avatar asked May 03 '09 01:05

Yen


3 Answers

It's pretty rare to be doing Java Web development without using some kind of MVC framework that'll delegate all views to JSPs (apart from PDF output and other corner cases) so you have:

  • JSPs;
  • Apache Velocity;
  • Freemarker.

Some Web frameworks like Tapestry and JSF ("Java Server Faces") are a little more like HTML views with extra tags.

JSPs are ultimately just compiled to servlets anyway and tend to be a more convenient form for outputting HTML. Generally speaking I'd use them as a minimum rather than writing a heap of out.println() statements in a servlet directly.

like image 169
cletus Avatar answered Nov 08 '22 12:11

cletus


I have successfully used Velocity for a number of years on a very small scale internal site.

Its easy to use and has a nice clean API. It handles burst of activity extremely well.

like image 2
Fortyrunner Avatar answered Nov 08 '22 13:11

Fortyrunner


Funny, I just saw a slightly similar question before. You can also use PHP pages via Quercus for your page rendering in Java.

like image 1
Clinton Avatar answered Nov 08 '22 14:11

Clinton