Yen
Yen

Reputation: 2186

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");
    }
}

Upvotes: 5

Views: 4290

Answers (4)

Fortyrunner
Fortyrunner

Reputation: 12782

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.

Upvotes: 2

Clinton
Clinton

Reputation: 2837

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

Upvotes: 1

alphazero
alphazero

Reputation: 27224

cletus is quite correct in his recommendations.

Freemarker (or velocity) are the solutions to use if you "simply" require template based rendering. They are quite effective. You can push up the complexity ladder an use JSPs.

I disagree that this is specifically limited to MVC pattern. At its most simplistic (and clearly this will not scale for large systems) you can have the same servlet service all requests, and choose a velocity/freemarker template, and populate the required context and render the template.

Upvotes: 0

cletus
cletus

Reputation: 625097

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:

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.

Upvotes: 5

Related Questions