package com.jarticles; import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; public class TemplateEngineDemo extends HttpServlet { private String documentPath = null; public void init(ServletConfig config) throws ServletException { super.init(config); documentPath = getInitParameter("documentPath"); // if no directory provided for loading the template, throwing the exception if (documentPath == null || documentPath.trim().length() == 0) { throw new UnavailableException (this, "No directory provided for loading the template."); } } private String getDocumentPath() { return documentPath; } public void service(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { long userId = -1; String userIdStr = req.getParameter("userId"); if (userIdStr != null) { try { userId = Long.parseLong(userIdStr); } catch (NumberFormatException nfe) { // so userId = -1; } } // find a user and load his information into a hashtable User user = User.findUserById(userId); Hashtable nvPairs = new Hashtable(); nvPairs.put("firstName", user.getFirstName()); nvPairs.put("lastName", user.getLastName()); nvPairs.put("sex", user.getSex()); nvPairs.put("position", user.getPosition()); // load a template and map the information of user into it String template = loadTemplate("userInfo.html"); String result = StringUtil.replace(template, nvPairs, ""); res.setContentType("text/html"); PrintWriter out = res.getWriter(); out.println(result); out.close(); } private final String loadTemplate(String fileName) throws IOException { String templatePath = getDocumentPath(); File tmplFile = new File(templatePath + fileName); BufferedReader in = new BufferedReader(new FileReader(tmplFile)); String data = null; StringBuffer buf = new StringBuffer(); while ( (data = in.readLine()) != null ) { buf.append(data); } return buf.toString(); } }