[EMAIL PROTECTED] writes:
>What if I have a tag called "firstname" and I want to query the databse
>using
>the username and password submited by the user to the the "firstname"?
>How
>would I register the "firstname" tag and what the get() method will
>return?  I
>can't really query the db in the get() method since I need the username
>and
>password.


Indeed, I forgot to include a few important parts in the demo code I
posted.

Here's a more complete example of how my system works.  Hope this helps
:-)  Let me know if further clarification is needed.

Let's say an application "MyServlet" has only two dynamic pages (for
demonstration purposes :-) : today.html and test.html

The TODAY file contains a regular HTML page including a tag
(@-(currentdate)-@) where we want to insert the current server date (ok,
not a very sophisticated feature, but hey, it's a demo..).  The TEST file
also contains a regular HTML page, but including a tag (@-(condition)-@)
where we want to insert "YES" if the servlet receives a request with a
"CONDITION" parameter containing "1", and "NO" if the servlet receives a
request with a "CONDITION" parameter containing "0" or any other value (or
if the parameter is completely missing).

To display the TODAY page, we will define an action called "getdate".  We
can then call up the dynamic page using a URL like this :

        http://www.yourdomain.com/MyServlet?action=get-date

To display the TEST page, we will define an action called "test".  We can
then call up the dynamic page using a URL like this :

        http://www.yourdomain.com/MyServlet?action=test
or
        http://www.yourdomain.com/MyServlet?action=test&condition=0
or
        http://www.yourdomain.com/MyServlet?action=test&condition=1

In order to let actions use data from the request to produce an answer
(which is usually what you want to do), we'll need to pass on the
HttpServletRequest object to the HTMLTemplate (that's the important I
forgot to include in the code I posted earlier).  The HTMLTemplate will
then pass on the HttpServletRequest object to its HTMLTag objects when
assembling a page for a specific request.  In this case, I have chosen to
wrap up the HttpServletRequest, HttpServletReponse and ServletOutputStream
in a MyRequest object to simplify parameters passed around.  This could
also allow you to easily pass additionnal information to the action
handlers without modifying each and every parameter relay.

The important thing to understand here is that actions (MyAction objects)
can do virtually ANYTHING.  They can be very simple like returning some
String defined at runtime, or they can be very complex, like querying an
SQL database for some information, and then validate that information
through an external online service or a bean or an proprietary algorythm
of some sort, and then format the data the way you want to, and then
gather some more data from some other sources based on what you received
from your database, and so on.  You get the idea.  It is up to you to
define how dynamic data is gathered and returned for a specific tag name.

In some cases however, there will be SOME html code embedded in the
servlet for obvious reasons.  For instance, generating a SELECT form
element can be done by the servlet, meaning that the SELECT tag's syntax
will be hardcoded  (example:  "<SELECT NAME=MyField>"+(your dynamic list
of options)+"</SELECT>").  You can then insert a simple tag in your HTML
and the complete SELECT tag will be inserted there at assembly time.  But
beside that, there isn't much more HTML code to include in your Java code.
 What I usually do is create a single Java class responsible for all minor
HTML manipulations.  I then program a method for writing a SELECT form
element, another for checkboxes, etc.  This way, all my small HTML parts
are in one place, so I know where to find them if I ever need to -
although the methods I put there are pretty generic, so they very rarely
need to be customized from one app to another.  But I need to point out
that if you want to, you could even put these simple HTML code parts in
external templates.  I just didn't bother with it yet since it so much
easier to work with that within the code once and then forget about it.

In the code below, I have also added the mechanism for making sure that
each HTMLTemplate is always in sync with its file on disk.

Anyway, here's my test servlet code, along with a modified copy of the
HTMLTemplate class I posted earlier.
Again, there might be a few syntax errors in there, I haven't compiled it
to find out.

Please feel free to comment.

--------------------

import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class MyServlet extends HttpServlet {

        public final String actionParameterName = "action";
        public Hashtable actions;

        public void init() {
                actions = new Hashtable();
                registerAction(new MyAction("get-date") {public void execute(MyRequest
request) {out.print(HTMLTemplate.html("MyHTMLFolder/today.html",req));}});
                registerAction(new MyAction("test") {public void execute(MyRequest
request) {out.print(HTMLTemplate.html("MyHTMLFolder/test.html",req));}});
        }

        public static void registerAction(String tagName, String filePath) {
                actions.put(action.name,action);
        }

        public void service(HttpServletRequest req, HttpServletResponse res) {
                try {
                        MyRequest request = new MyRequest(req,res);
                        String actionName = request.param(actionParameterName);
                        MyAction action = (MyAction )actions.get(actionName);
                        if (action==null) { ... some code here that will get executed 
if action
can't be found ... ; return;}
                        action.execute(request);
                } catch (Exception e) {return;}
        }

        public class MyAction {

                public String name;

                public MyAction(String name) {
                        this.name = name;
                }

                public void execute(MyRequest request) {}

        }

}

public class MyRequest {

        HttpServletRequest req;
        HttpServletResponse res;
        ServletOutputStream out

        public MyRequest(HttpServletRequest req, HttpServletResponse res) {
                this.req = req;
                this.res = res;
                this.out = res.getOutputStream();
        }

        public String param(String name) {
                String param = req.getParameter(name);
                return param==null?"":param;
        }

}


public class HTMLTemplate {

        /* STATIC STUFF */

        public static Hashtable tags;
        public static Hashtable cache = new Hashtable();

        public static synchronized void initialize() {
                if (tags != null) {return;}
                tags = new Hashtable();
                registerTag(new HTMLTag("currentdate") {public String get(MyRequest
request) {
                        Date todaySDate = new Date();
                        String todaySDateString = todaySDate.toString();
                        return todaySDateString;
                }});
                registerTag(new HTMLTag("condition") {public String get(MyRequest
request) {
                        String conditionParameter = request.param("condition");
                        return conditionParameter.equals("1")?"YES":"NO";
                }});
        }

        public static void registerTag(HTMLTag tag) {
                tags.put(tag.name,tag);
        }

        public static void registerTemplate(HTMLTemplate template) {
                templates.put(template.filePath,template);
        }

        public static String html(String templatePath, MyRequest request) {
                HTMLTemplate template = templates.get(templatePath)==null?new
HTMLTemplate(file):templates.get(templatePath);
                return template.assemble(request);
        }

        /* INSTANCE STUFF */

        public String filePath;
        public String[] parts;
        public int initialTemplateSize;
        public long version = 0;

        public HTMLTemplate(String templatePath) {
                filePath = templatePath;
                load();
                HTMLTemplate.registerTemplate(this);
        }

        public void load() {
                if (tags == null) {HTMLTemplate .initialize();}
                String content = read(new File(filePath));
                parts = disassemble(content);
        }

        public String read(File file) {
                /* ... some code here that reads a file and returns the content as a
String ... */
                initialTemplateSize = (int)file.length();
                version = file.lastModified();
        }

        public String[] disassemble(String content) {
                /*
                        ... some code here that takes apart the content and returns a 
String[]
array...
                        - array[0] : html code
                        - array[1] : first tag name
                        - array[2] : html code
                        - array[3] : second tag name
                        and so on...
                */
        }

        public String assemble(MyRequest request) {
                File file = new File(filePath);
                long currentVersion = file.lastModified();
                if (version!=currentVersion) {load();}
                StringBuffer buf = new StringBuffer(initialTemplateSize);
                boolean isTag = false;
                for (int i = 0;i < parts.length;i++) {
                        if (isTag) {
                                HTMLTag tag = (HTMLTag)tags.get(parts[i]);
                                if (tag!=null) {buf.append(tag.get(request));}
                        } else {
                                buf.append(parts[i]);
                        }
                        isTag = !isTag;
                }
        }

        public class HTMLTag {

                public String name;

                public HTMLTag(String name) {
                        this.name = name;
                }

                public String get(MyRequest request) {
                        return "";
                }

        }

}



       Sylvain Pedneault , superviseur technique

       AQUOPS ,  7400, boul. Saint-Laurent, bur. 528  Montr�al, QC  H2R 2Y1
       T�l�phone:  (514) 948-1234 p.232 - T�l�copieur:  (514) 948-1231
       Courriel:  [EMAIL PROTECTED]    -    Web:
www.aquops.qc.ca

___________________________________________________________________________
To unsubscribe, send email to [EMAIL PROTECTED] and include in the body
of the message "signoff SERVLET-INTEREST".

Archives: http://archives.java.sun.com/archives/servlet-interest.html
Resources: http://java.sun.com/products/servlet/external-resources.html
LISTSERV Help: http://www.lsoft.com/manuals/user/user.html

Reply via email to