views:

103

answers:

4

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");
    }
}
+2  A: 

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.

cletus
Great answer. Thanks for all the info. I like the look of Apache Velocity. That looks close to the Ruby templating options I was trying to approximate (erb, haml). JSF is a little like CFML. Freemarker I'm not sure - the website doesn't look so professional, makes me nervous. Tapestry seems involved - have to study up on that. I may end up sticking with JSPs as you hinted. Thanks.
Yen
A: 

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.

+1  A: 

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

Clinton
+2  A: 

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.

Fortyrunner