Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Html templates and servlets

Posted on 1999-07-27
12
Medium Priority
?
221 Views
Last Modified: 2013-11-24
I'm trying to come up with a neater way of incorporating html coding into servlets, I know there r several products out there that does this but i want to do it in the simplest of manner.

The only way i can think of is by saving chunks of html codes into files and making these files sorta like a template for each segment of the homepage thus the servlet would select which chunk of codes to load based on the request.

Is there any sites out there that explains this? Can u guys link me to sites that explains SSI with Servlets and its likes..

ok... thanks a bundle.
0
Comment
Question by:load_o_crap
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
12 Comments
 
LVL 3

Expert Comment

by:slok
ID: 1247196
0
 
LVL 16

Expert Comment

by:heyhey_
ID: 1247197
check www.javasoft.com for some Java Server Pages (JSP) info
0
 

Author Comment

by:load_o_crap
ID: 1247198
erm... so far the one of the better sites is the ibm tutorial.

could u guys show me  some working examples on how to insert specific file templates...


0
Stack Overflow Podcast - Developer Story

Welcome to the Stack Overflow podcast recorded Thursday July 20 at Stack Overflow Headquearters in NYC. Your hosts today are podcast regulars Jay Hanlon, David Fullerton, and Ilana Yitzhaki, plus the quite irregular Matt Sherman (Stack Overflow Engineering Manager extraordinaire)

 
LVL 16

Expert Comment

by:heyhey_
ID: 1247199
it's a long story ...
what's the exact problem ?

load template file - convert it to String, replace all the '%user%' strings with curent user name and write the result String to the Socket output stream.
0
 

Author Comment

by:load_o_crap
ID: 1247200
well ok... long story.

Lets say i have a file containing a tags for an imagemap and the <img src> for the image... i'll call the file imagemap01.template.

so, how do i say insert this template into my document.

<%insert=imagemap01.template%>

or if i'm doing some formatting would it be

<table>
<tr>
<td> <%insert=imagemap01.template%> </td>
</tr>
<table>


0
 
LVL 16

Expert Comment

by:heyhey_
ID: 1247201
you can load the whole file into a String, parse is yourself and replace all the tags. or you want some existing server application to handle it ?
0
 

Author Comment

by:load_o_crap
ID: 1247202
loading the whole file into a string is a cool way to do it... atleast for a start...

some sample coding would be nice
i'll increase the points to 200 if its a working model!!! :)

mine for some reason didn't.. i got a blank file when it should have displayed
the text from the file...


0
 
LVL 16

Expert Comment

by:heyhey_
ID: 1247203
ok I'm posting some old code .... I'll post some comments after it.


import java.io.*;
import java.util.*;
import testutor.backend.ServerConfig;


public class HTMLTemplateManager1
{
    private static String htmlTemplateFile = "template.html";
    public static final String TEMPLATE_MAINPAGE = "mainpage";
    public static final String TEMPLATE_LOGINPAGE = "loginpage";
    public static final String TEMPLATE_MAINERRORPAGE =  "mainerrorpage";

    public static String[] standardTemplates =
       {TEMPLATE_MAINPAGE, TEMPLATE_LOGINPAGE, TEMPLATE_MAINERRORPAGE};    

    public static Hashtable templates = new Hashtable();
    public static Hashtable lines = new Hashtable();
    public static Hashtable substs = new Hashtable();
               
    public static String getTemplate(String templateName)
    {
        String st = (String)templates.get(templateName);
        if (st != null)
            return st;
        else
            return "";
    }
   
    public static void init()
    {
        try {
           
            htmlTemplateFile = ServerConfig.getHtmlTemplateFile();
            loadTemplates();
//            printTemplates ();
            expandTemplates();
//            printTemplates ();
            checkForStandardTemplates();
            getStandardDefines();
        } catch (Exception e)
        {
            log("HTMLTemplateManager can't initialize. ", e);
            if (e instanceof RuntimeException)
                throw(RuntimeException)e;
            else
                throw new RuntimeException ("HTMLTemplateManager can't initialize: " + e.getMessage());
        }
       
    }
   
  public static void getStandardDefines() throws IOException
  {
    String defines = (String)templates.get("standarddefines");
    substs.put("%appleturltag:)%", ServerConfig.getAppletArchiveTag());
    substs.put("%redirecturl%", ServerConfig.getRedirectURL());    
   
    if (defines == null)
    {
      log("Warning:standarddefines section does on exist in templates file." );
      return;
    }
   
    BufferedReader br = new BufferedReader(new StringReader(defines));
    String st, st1;
    int n;
    while ((st = br.readLine()) != null)
    {
      st = st.trim();
      if (st.startsWith("<!--") && (n = st.indexOf("%define%")) != -1)
      {
        StringTokenizer tokens = new StringTokenizer (st.substring(n));
        tokens.nextToken(); // the %define%
        String key = tokens.nextToken();
        n = st.indexOf(key);
       
        st1 = st.substring(n + key.length());
        n = st1.indexOf("-->");
        st1 = st1.substring(0, n);
        substs.put(key, st1.trim());
      }
    }
  }
   
/*
    public static void initStandardSubstitutions()
    {
//        substs.put("%totalwidth%", "780");
        substs.put("%totalwidthright%", "650");
        substs.put("%totalwidthleft%", "130");
//        substs.put("%servleturl%", "/servlet/TestServlet15");
        substs.put("%bgcolor%", "#C0C0C0");
        substs.put("%bgcolorleft%", "#b0b0d0");
//        substs.put("%bgcolorleft%", "#a080d0");
        substs.put("%appleturltag:)%", ServerConfig.getAppletArchiveTag());
        substs.put("%redirecturl%", ServerConfig.getRedirectURL());
    }
*/    
    public static void setStandardSubstitution(String name, String val)
    {
        substs.put(name, val);
    }

    public static void setServletURL(String val)
    {
        substs.put("%servleturl%", val);
    }
/*
    public static void setAppletURL(String val)
    {
        substs.put("%servleturl%", val);
    }
  */  

    public static void printTemplates ()
    {
        log("printTemplates");
        String key, value;
        Enumeration e = templates.keys();
        while (e.hasMoreElements())
        {
            key = (String) e.nextElement();
            value = getTemplate(key);
            log("key = " + key + ", value = " + value);
         }
    }
    public static String reformatWithStandartSubstitutions(String orig)
    {
        String st = orig;
        String key, value;
        Enumeration e = substs.keys();
        while (e.hasMoreElements())
        {
            key = (String) e.nextElement();
            value = (String)substs.get(key);
            st = replaceAllStrings(st, key, value);
        }
        return st;
    }
   
    public static String replaceAllStrings(String orig, String from, String to)
    {
        int n;
        while ( (n = orig.indexOf(from)) != -1)
        {
            String t = "" + orig.substring(0, n) + to + orig.substring(n + from.length());
            orig = t;
        }
        return orig;
    }

/*
  exapnds all the include directives. throws Exception if it detects include cycle.
*/    
  private static void expandTemplates() throws IOException
  {
    String st;
    String key;
    boolean hasFound;
    do
    {
      hasFound = false;
      Enumeration e = templates.keys();
      while (e.hasMoreElements())
      {
        hasFound = false;
        key = (String) e.nextElement();
//        log("key = " + key);
        if (expandTemplate(key))
          hasFound = true;
      }
    } while (hasFound != false);
  }
 
  private static Hashtable expandHash = new Hashtable();
  private static void log(String s)
  {
    log(s, null);
  }
  private static void log(String s, Exception e)
  {
    System.out.println(" " + s);
    if (e != null) e.printStackTrace();
  }
  private static boolean expandTemplate(String templateName) throws IOException
  {
    String st;
    int n;
//    log("expanding " + templateName);
    String value = (String)templates.get(templateName);
   
    if (value == null || value.indexOf("%include%") == -1) return false;
    if (expandHash.get(templateName) != null)
      throw new RuntimeException("Cyclic include detected while expanding template " + templateName);
    expandHash.put(templateName, "hi");
   
    StringBuffer buf = new StringBuffer();  
    BufferedReader br = new BufferedReader(new StringReader(value));
//    log("reading lines ...");
    while ((st = br.readLine()) != null)
    {
      String st1 = st.trim();
      if (st1.length() == 0) continue;
      if (st1.startsWith("<!--"))
      {
        if ((n = st1.indexOf("%include%")) != -1)
        {
//          log("%include% detected");
          StringTokenizer tokens = new StringTokenizer (st1.substring(n));
          tokens.nextToken(); // the %include%
          String subTemplate = tokens.nextToken();
          if (!"-->".equals(tokens.nextToken()))
              throw(new RuntimeException ("Bad include directive in template " + templateName));
         
          expandTemplate(subTemplate);
          st = (String)templates.get(subTemplate);
          if (st == null)
              throw(new RuntimeException ("Can't expand include directive in template " + templateName + " - subTemplate " + subTemplate + " does not exists."));
        }
        else if ((n = st1.indexOf("%define%")) != -1)
        {
         
        }
        else
          continue; // clear all the comments
      }
      if (buf.length() != 0) buf.append("\r\n");
      buf.append(st);
    }
    templates.put(templateName, buf.toString());
    expandHash.remove(templateName);
    return true;
  }
/*
  loads a bunch of tempalte definitions from a file
*/    
    private static void loadTemplates() throws IOException
    {
        String curSectionName = null;        
        StringBuffer curTemplate = new StringBuffer();
   
        BufferedReader br = new BufferedReader (new FileReader(htmlTemplateFile));
        String st;
        int n;
        int line = 0;
                   
        while ((st = br.readLine()) != null)
        {
           line++;
           String st1 = st.trim();
           if (st1.startsWith("<!--") && ((n = st1.indexOf("%section%")) != -1))
           {
  //           log(" " + line + ": " + st1);
                // section tag found !!
                if (curSectionName != null)
                {
                  if (templates.get(curSectionName) != null)
                    log("loadTemplates Warning: section already exists: " + curSectionName);
                  else
                    templates.put(curSectionName, curTemplate.toString());
                }
                curTemplate = new StringBuffer();
               
                StringTokenizer tokens = new StringTokenizer (st1.substring(n));
                tokens.nextToken();
                if (!tokens.hasMoreTokens())
                    throw(new RuntimeException ("Invalid template file format at line " + line));
                curSectionName = tokens.nextToken();
                lines.put(curSectionName, new Integer(line));
           }
           else
           {
               curTemplate.append("\r\n");
               curTemplate.append(st);
           }
        }
       
        if (curSectionName != null)
        {
          if (templates.get(curSectionName) != null)
            log("loadTemplates Warning: section already exists: " + curSectionName);
          else
            templates.put(curSectionName, curTemplate.toString());
        }
       
        br.close();
    }
 
 /*
   checks if several standard tempaltes are loaded.
   throws Exception if some standard template is not loaded
 */
     public static void checkForStandardTemplates()
    {
        int n = standardTemplates.length;
        for (int i = 0; i < n; i++)
        {
            if (templates.get(standardTemplates[i]) == null)
            {
                throw new RuntimeException ("HTMLTemplateManager can't fine template [" + i +
                    "]: " + standardTemplates[i]);
                   
            }
        }
    }
       
    public static String getMainPage()
    {
        return getTemplate(TEMPLATE_MAINPAGE);
    }    
    public static String getLoginPage()
    {
        return getTemplate(TEMPLATE_LOGINPAGE);
    }    
    public static String getMainErrorPage()
    {
        return getTemplate(TEMPLATE_MAINERRORPAGE);
    }
   

}
0
 
LVL 16

Expert Comment

by:heyhey_
ID: 1247204
you won't be able to compile the class directly, because you don't have the ServerConfig file
(this is a simple configuration object)
 
Hashtable templates is the hashtable with the template names + tamplate bodies
Hashtable lines is helper Hashtable - template name + start line (so that you can print nice erro messages)
Hashtable substs contains the substitutions the substitution

loadTemplates() loads the template definitons from a file
expandTemplates() expands the %include% directives
checkForStandardTemplates() checks if some standard templates are loaded
getStandardDefines() loads some substitutions from a template named standarddefines
 
setStandardSubstitution() adds another substitution
reformatWithStandartSubstitutions(String orig)replaces all the substitutions inside some string (template)
replaceAllStrings(...) replaces some substitution (ugly implementation - you can use String.replace() instead)

 
a sample template file
 
<!--- %section% standarddefines -->
    <!--- %define% %totalwidthleft% 130 -->
    <!--- %define% %totalwidthright% 650 -->
    <!--- %define% %bgcolor% #C0C0C0 -->
    <!--- %define% %bgcolorleft% #b0b0d0 -->    
    <!--- %define% %bgcolor2% #eeeeff -->

    <!--- %define % %bgcolor% #a0a0a0 -->
    <!--- %define % %bgcolorleft% #d0b0c0 -->    
<!--- defines end -->

<!--- %section% mainpage -->
    <!--- %include% commonheader -->
    <!--- %include% mainleftmenu -->
    <!--- %include% mainsubpage -->
    <!--- %include% commonfooter -->
<!--- mainpage end -->
 
<!--- %section% commonheader -->
    <html>
    <head>
        <title>Testutor - %title% </title>
    </head>
   
    <!--- start of header --->
    <body bgcolor="%bgcolor%" text="#000000" topmargin=0 leftmargin=0>
        <table  cellpadding=16 cellspacing=1 border=0>
            <tr valign=top>
                <td width=%totalwidthleft% height=30 valign=bottom align=center> <font size=5 color="#ff0000">La-La</font> </td>
                <td height=30 align=center valign=bottom bgcolor="#000000"> <font size=5 color="#f0f0f0">  &nbsp; %header% </font> </td>
            </tr>
    <!--- end of header --->        
   
    <tr valign=top>
<!--- commonheader end -->
 
   
and so on ...
 
the code is ugly and uncompilable (it's part of some old project), but maybe, you'll find some interesting solutions
  (or some 'ugly' pieces of code ...), but ...
   
if you need more help, you'd better post your code (or send it directly to heyhey_iname.com)
 
best regards
  heyhey
0
 
LVL 16

Accepted Solution

by:
heyhey_ earned 400 total points
ID: 1247205
answer.
0
 

Author Comment

by:load_o_crap
ID: 2119025
well... i'll take it anyway, after a while
i've worked with using Beans to incorporate to actually compartmentalize
the different components... but ur ideas provided some start...

thanks anyway.
0
 
LVL 1

Expert Comment

by:Moondancer
ID: 6830746
This question was awarded, but never cleared due to the JSP-500 errors of that time.  It was "stuck" against userID -1 versus the intended expert whom you awarded.  This corrects the problem and the expert will now receive these points; points verified.

Please click on your Member Profile and select "View Question History" to navigate through any open or locked questions you may have to update and finalize them.  If you are an EE Pro user, you can also choose Power Search to find all your open questions.

This is the Community Support link, if help is needed, along with the link to All Topics which reflects many TAs recently added.

http://www.experts-exchange.com/jsp/qList.jsp?ta=commspt
http://www.experts-exchange.com/jsp/zonesAll.jsp
 
Thank you,
Moondancer
Moderator @ Experts Exchange
0

Featured Post

The top UI technologies you need to be aware of

An important part of the job as a front-end developer is to stay up to date and in contact with new tools, trends and workflows. That’s why you cannot miss this upcoming webinar to explore the latest trends in UI technologies!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.
Suggested Courses

715 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question