load_o_crap
asked on
Html templates and servlets
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.
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.
check www.javasoft.com for some Java Server Pages (JSP) info
ASKER
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...
could u guys show me some working examples on how to insert specific file templates...
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.
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.
ASKER
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.templa te%>
or if i'm doing some formatting would it be
<table>
<tr>
<td> <%insert=imagemap01.templa te%> </td>
</tr>
<table>
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.templa
or if i'm doing some formatting would it be
<table>
<tr>
<td> <%insert=imagemap01.templa
</tr>
<table>
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 ?
ASKER
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...
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...
ok I'm posting some old code .... I'll post some comments after it.
import java.io.*;
import java.util.*;
import testutor.backend.ServerCon fig;
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(temp lateName);
if (st != null)
return st;
else
return "";
}
public static void init()
{
try {
htmlTemplateFile = ServerConfig.getHtmlTempla teFile();
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("sta ndarddefin es");
substs.put("%appleturltag: )%", ServerConfig.getAppletArch iveTag());
substs.put("%redirecturl%" , ServerConfig.getRedirectUR L());
if (defines == null)
{
log("Warning:standarddefin es 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("%totalwidthrig ht%", "650");
substs.put("%totalwidthlef t%", "130");
// substs.put("%servleturl%", "/servlet/TestServlet15");
substs.put("%bgcolor%", "#C0C0C0");
substs.put("%bgcolorleft%" , "#b0b0d0");
// substs.put("%bgcolorleft%" , "#a080d0");
substs.put("%appleturltag: )%", ServerConfig.getAppletArch iveTag());
substs.put("%redirecturl%" , ServerConfig.getRedirectUR L());
}
*/
public static void setStandardSubstitution(St ring 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 reformatWithStandartSubsti tutions(St ring 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(temp lateName);
if (value == null || value.indexOf("%include%") == -1) return false;
if (expandHash.get(templateNa me) != null)
throw new RuntimeException("Cyclic include detected while expanding template " + templateName);
expandHash.put(templateNam e, "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.next Token()))
throw(new RuntimeException ("Bad include directive in template " + templateName));
expandTemplate(subTemplate );
st = (String)templates.get(subT emplate);
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(template Name);
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(htmlTemplateFil e));
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(curSectionN ame) != null)
log("loadTemplates Warning: section already exists: " + curSectionName);
else
templates.put(curSectionNa me, 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(curSectionN ame) != null)
log("loadTemplates Warning: section already exists: " + curSectionName);
else
templates.put(curSectionNa me, 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(standardTem plates[i]) == null)
{
throw new RuntimeException ("HTMLTemplateManager can't fine template [" + i +
"]: " + standardTemplates[i]);
}
}
}
public static String getMainPage()
{
return getTemplate(TEMPLATE_MAINP AGE);
}
public static String getLoginPage()
{
return getTemplate(TEMPLATE_LOGIN PAGE);
}
public static String getMainErrorPage()
{
return getTemplate(TEMPLATE_MAINE RRORPAGE);
}
}
import java.io.*;
import java.util.*;
import testutor.backend.ServerCon
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(temp
if (st != null)
return st;
else
return "";
}
public static void init()
{
try {
htmlTemplateFile = ServerConfig.getHtmlTempla
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("sta
substs.put("%appleturltag:
substs.put("%redirecturl%"
if (defines == null)
{
log("Warning:standarddefin
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%",
substs.put("%totalwidthrig
substs.put("%totalwidthlef
// substs.put("%servleturl%",
substs.put("%bgcolor%", "#C0C0C0");
substs.put("%bgcolorleft%"
// substs.put("%bgcolorleft%"
substs.put("%appleturltag:
substs.put("%redirecturl%"
}
*/
public static void setStandardSubstitution(St
{
substs.put(name, val);
}
public static void setServletURL(String val)
{
substs.put("%servleturl%",
}
/*
public static void setAppletURL(String val)
{
substs.put("%servleturl%",
}
*/
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 reformatWithStandartSubsti
{
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(temp
if (value == null || value.indexOf("%include%")
if (expandHash.get(templateNa
throw new RuntimeException("Cyclic include detected while expanding template " + templateName);
expandHash.put(templateNam
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.next
throw(new RuntimeException ("Bad include directive in template " + templateName));
expandTemplate(subTemplate
st = (String)templates.get(subT
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
expandHash.remove(template
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(htmlTemplateFil
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(curSectionN
log("loadTemplates Warning: section already exists: " + curSectionName);
else
templates.put(curSectionNa
}
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(curSectionN
log("loadTemplates Warning: section already exists: " + curSectionName);
else
templates.put(curSectionNa
}
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(standardTem
{
throw new RuntimeException ("HTMLTemplateManager can't fine template [" + i +
"]: " + standardTemplates[i]);
}
}
}
public static String getMainPage()
{
return getTemplate(TEMPLATE_MAINP
}
public static String getLoginPage()
{
return getTemplate(TEMPLATE_LOGIN
}
public static String getMainErrorPage()
{
return getTemplate(TEMPLATE_MAINE
}
}
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
reformatWithStandartSubsti tutions(St ring 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</fon t> </td>
<td height=30 align=center valign=bottom bgcolor="#000000"> <font size=5 color="#f0f0f0"> %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
(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(
getStandardDefines() loads some substitutions from a template named standarddefines
setStandardSubstitution() adds another substitution
reformatWithStandartSubsti
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</fon
<td height=30 align=center valign=bottom bgcolor="#000000"> <font size=5 color="#f0f0f0"> %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
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
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.
i've worked with using Beans to incorporate to actually compartmentalize
the different components... but ur ideas provided some start...
thanks anyway.
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.
https://www.experts-exchange.com/jsp/qList.jsp?ta=commspt
https://www.experts-exchange.com/jsp/zonesAll.jsp
Thank you,
Moondancer
Moderator @ Experts Exchange
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.
https://www.experts-exchange.com/jsp/qList.jsp?ta=commspt
https://www.experts-exchange.com/jsp/zonesAll.jsp
Thank you,
Moondancer
Moderator @ Experts Exchange
www.servletcentral.com
these article.. will interest u...
http://www.servletcentral.com/1998-12/designprocess.dchtml
http://www.servletcentral.com/1999-01/design.dchtml