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