You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@velocity.apache.org by Gabriel Sidler <si...@teamup.ch> on 2002/02/22 11:01:17 UTC

Re: [VelTools] Velocity View API for Struts [Phase 2]

Nathan Bubna wrote:
[..]
> > Any better ideas are highly welcome.
> 
> did you give any thought to my suggestion of renaming the context key for
> MessageTool instead of the one for ActionMessagesTool?  my suggestion was to
> change '$msg' to '$i18n' or '$text' (or something better if someone thinks
> of one) and to let ActionMessagesTool keep '$msgs'.
>
> whaddaya think?

Yes, I gave it some thought. The MessageTool will easily be the most used
context tool in any Struts application. The correspoding JSP tag is <bean:message .../>
In contrast, ActionMessages is new. Noboby is using it yet. So I'd rather come up
with some creative naming for action messages instead of for the well established
message resources.

I actually begin to like your proposed $actionmsgs. Message tool ($msg) typically 
will be used many times a page. Keeping it short is good. $actionmsgs typically is 
used once per template. Having a slightly longer name is not an issue. The 
potential for confusion between $msg and $actionmsgs is small.

I propose that we go with these names for now. We can always come back and 
change later.

Gabe




> 
> Nathan Bubna
> nathan@esha.com
> 
> --
> To unsubscribe, e-mail:   <ma...@jakarta.apache.org>
> For additional commands, e-mail: <ma...@jakarta.apache.org>

--
Gabriel Sidler
Software Engineer, Eivycom GmbH, Zurich, Switzerland

--
To unsubscribe, e-mail:   <ma...@jakarta.apache.org>
For additional commands, e-mail: <ma...@jakarta.apache.org>


Re: [VelTools] Velocity View API for Struts

Posted by Gabriel Sidler <si...@teamup.ch>.
Nathan Bubna wrote:
> 
> Gabriel Sidler wrote:
> > Hi,
> > I have consolidated all past discussions in phase 1 and phase 2
> > into this latest draft v0.4. Discard all previous drafts.
> >
> > I added a section 2) on auto-population of the context. This documents
> > objects that are made available automatically in the Velocity context.
> > It represents the status of the current prototype.
> >
> > I welcome any feedback.
> 
> +1 on everything.  i like where things are headed!

Ok, that's great.

I am working now on turning the draft into code, documentation and
examples. In the process I came across several minor things that seem 
suboptimal in the current draft. Expect some more details later this
week.

Gabe

--
Gabriel Sidler
Software Engineer, Eivycom GmbH, Zurich, Switzerland

--
To unsubscribe, e-mail:   <ma...@jakarta.apache.org>
For additional commands, e-mail: <ma...@jakarta.apache.org>


Re: [VelTools] Velocity View API for Struts

Posted by Nathan Bubna <na...@esha.com>.
Gabriel Sidler wrote: 
> Hi,
> I have consolidated all past discussions in phase 1 and phase 2 
> into this latest draft v0.4. Discard all previous drafts.
> 
> I added a section 2) on auto-population of the context. This documents
> objects that are made available automatically in the Velocity context.
> It represents the status of the current prototype.
> 
> I welcome any feedback. 

+1 on everything.  i like where things are headed!
 
> From my point of view we are now pretty close to a stable version and
> can soon move to the design, implementation and documentation.
> 
> Gabe



--
To unsubscribe, e-mail:   <ma...@jakarta.apache.org>
For additional commands, e-mail: <ma...@jakarta.apache.org>


Re: [VelTools] Velocity View API for Struts

Posted by Gabriel Sidler <si...@teamup.ch>.
Hi,
I have consolidated all past discussions in phase 1 and phase 2 
into this latest draft v0.4. Discard all previous drafts.

I added a section 2) on auto-population of the context. This documents
objects that are made available automatically in the Velocity context.
It represents the status of the current prototype.

I welcome any feedback. 

>From my point of view we are now pretty close to a stable version and
can soon move to the design, implementation and documentation.

Gabe


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

VELOCITY VIEW API FOR STRUTS
============================

Version 0.4, 22-Feb-2002


This document describes the Velocity View API for Struts.

1) Context Tools

2) Auto-Population of the Velocity Context




1) Context Tools
----------------

The following five context tools have been defined:

1.1) LinkTool - Support for working with hyper links, translation between logical
                names and the corresponding paths

1.2) MessageTool - Support for working with Struts message resources

1.3) ErrorsTool - Support for working with Struts error messages

1.4) ActionMessagesTool - Support for working with Struts action messages

1.5) FormTool - Support for working with HTML forms in templates



1.1) LinkTool
--------------

Struts supports a configurable level of indirection between the URL of a 
request and the handler of that request. For example, a URL of /main.do 
may be mapped by configuration to a handler class.
Furthermore, Struts knows the concept of 'forwards'. A 'forward' is a name
for a request target, such as a request handler or simply a web page. 
This configurable mapping of logical targets to actual targets allows
one to avoid hard-coded URLs in templates. All the logical links between
the different views of an application can be maintained in a configuration
file. 

The LinkTool provides methods to work with hyperlinks:

o translate logical names to real paths
o construct and encode query strings
o retrieve server, port and path info for the current request

Class: org.apache.velocity.tools.struts.LinkTool

Recommended name in context: $link

Methods:

public LinkTool setPath(String path)

    Returns a copy of this link with the given path setting.
    No conversions are applied to path.
    Note: It is Struts recommended practice to forward to
    actions or forwards, but not directly to templates as this
    bypassed the Struts controller. Consider using setAction() 
    or setForward() instead.


public LinkTool setAction(String action) 

    Returns a copy of this link with the given action name
    converted into a server-relative path (as per configuration
    in struts-config.xml).
    Example: 
    <form name="login" action='$link.setAction("login")'>
    produces something like
    <form name="login" action="/myapp/actions/loginaction">


public LinkTool setForward(String forward)

    Returns a copy of this link with the given forward name
    converted into a server-relative path (as per configuration
    in struts-config.xml).
    Example: 
    <a href='$link.setForward("home")'>Home</a>
    produces something like
    <a href="/myapp/templates/index.vm">Home</a>
        

public LinkTool setAbsolute(String path)

    Returns a copy of this link with the specified context-relative 
    path converted to an absolute path.
    Example:
    <a href='$link.setAbsolute("/templates/login/index.vm")'></a>
    produces something like
    <a href="http://myserver:port/myapp/templates/login/index.vm">Login Page</a>
    

public LinkTool addQueryData(String key, Object value)

    Adds a key/value pair to the query data. This returns a new LinkTool 
    containing both a copy of this LinkTool's query data and the new data.
    This makes repeated use in Velocity templates much easy. Query data is
    URL encoded before it is appended.


public String getPath()

    Returns the current path set for this link as set by
    the methods setPath(), setAction(), setForward() or
    setAbsolute(). Any conversions have been applied.
    

public String getQueryData()

    Returns this link's query data as an url-encoded string
    e.g. "key=value&foo=this+is+encoded".


public String getServerPath()

    Returns the server & context url, e.g. "http://myserver.net/myapp".


public String getBaseRef()

    Returns a full reference to the template without any query data.
    e.g. "http://myserver.net/myapp/stuff/View.vm"
    NOTE! This returns that base ref of the last request. This will NOT 
    represent any path or query data set for this LinkTool! A typical 
    application of this is with the HTML base tag.
    e.g. <base href="$tool.baseRef">


public String toString()

    Returns the full URL that's been built with this tool
    e.g. "http://myserver.net/myapp/stuff/View.vm?id=42&type=blue"
    Typically it is not necessary to call this method explicitely.
    Velocity will call the toString() method automatically to 
    obtain a representable version of this object.



1.2) MessageTool
----------------

Struts supports internationalized messages. The messages are stored
in NVP files by language. The following methods operate on these message 
files.

Class: org.apache.velocity.tools.struts.MessageTool

Recommended name in context: $msg

Methods:

public String get(String key)

    Return the localized message for the specified key.
    Example:
    <input type="submit" name="newbutton" value='$msg.newpatient'/>
    looks up a message with key="newpatient" and renders something like
    <input type="submit" name="newbutton" value='Register new patient'/>


public String get(String key, Object args[])

    Same as above, but supports parametric message strings, for example
    for a message resource defined as:
    warning.quota=Your mail folder is {0} MB above the limit of {1} MB.
    {0} and {1} are replaced by the values passed. Up to five replacement 
    parameters are supported.


public boolean exists(String key)

    Return true if a message string for the specified message key
    is present for the user's Locale.


public Locale getLocale()

    Retrieve and return the Locale for the user. If a Locale is
    not found, the default locale is returned. Note: Struts' locale 
    is not request.getLocale().
    


1.3) ErrorsTool
---------------

Errors may stem from the validation of a submitted form or from the 
processing of the request. If there are errors, they are made available
to the view to render. A few aspects about errors are:
o Error message strings are looked up in the message resources. Support 
  for internationalized messages is provided.
o Error messages can have up to five replacement parameters.
o Errors have a property that marks them as either 'global errors' (meaning 
  that they apply to an entire form) or 'specific errors' (meaning that they 
  are specific to one of the form elements). This allows to position error 
  messages precisely where the error occurred on the form.

Class: org.apache.velocity.tools.struts.ErrorsTool

Recommended name in context: $errors

Methods:

public boolean exist() 

    Returns true if there are errors queued, otherwise false.


public int getSize() 

    Returns the number of error messages queued.


public int getSize(String property) 

    Returns the number of error messages queued for a particular property.


public HashMap getAll() 

    Returns a HashMap of localized error messages for all errors queued. 
    A typical application would use a script similar to the following to 
    output the error messages.
    Example:
    <ul>
    #foreach ($e in $errors.all )
      <li>$e</li>
    #end
    </ul>


public HashMap get(String property) 

    Same as above but only the error messages for a particular property 
    are retrieved and returned.


Note:
To output a fully formatted error message similar to what the JSP tag 
html:errors does, it is recommended to utilize a VelociMacro. The 
following VelociMacro produces the same output as the html:errors JSP
tag:

#macro ( errorMarkup )
    #if ($errors.exist )
        <ul>
        #foreach ($e in $errors.all )
            <li>$e</li>
        #end
        </ul>
    #end
#end

The following macro generates error markup for a particular property:

#macro ( errorMarkup $property)
    #if ($errors.exist($property) )
        <ul>
        #foreach ($e in $errors.get($property) )
            <li>$e</li>
        #end
        </ul>
    #end
#end



1.4 ActionMessagesTool
----------------------

Action messages generalize the concept of error messages to include 
all kinds of messages that an action might want to pass to the view.
So, every error message is an action message, but not every action
message is an error message. The set of methods are the same as for
handling error messages. Note: Action messages are not to be confused
with the message resources used for internationalized output.

Action messages are new in Struts 1.1. This tool will not work with
Struts versions prior to 1.1.

Class: org.apache.velocity.tools.struts.ActionMessagesTool

Recommended name in context: $actionmsgs

Methods: 

public boolean exist();

    Returns true if there are messages (stored under MESSAGE_KEY) OR
    errors (stored under ERROR_KEY) queued, otherwise false.


public int getSize();

    Returns the total number of messages and errors (stored under MESSAGE_KEY
    and ERROR_KEY).


public int getSize(String property);

    Returns the total number of messages and errors (stored under MESSAGE_KEY
    and ERROR_KEY) for the specified property.


public HashMap getAll();

    Returns a HashMap of localized messages and error messages (stored under
    MESSAGE_KEY and ERROR_KEY). 


public HashMap get(String property);

    Same as above but only messages and error for a particular property
    are returned.


Examples:

To output all queued action messages:
#if ($actionmsgs.exist() )
    <p>There are $actionmsgs.size() messages.</p>    
    <ul>
    #foreach ($m in $actionmsgs.all() )
        <li>$m</li>
    #end
    </ul>
#end

To output all queued action messages for a specific property 'password':
#if ($actionmsgs.exist("password") )
    <ul>
    #foreach ($m in $actionmsgs.password )
        <li>$m</li>
    #end
    </ul>
#end



1.5) FormTool
-------------

Struts has support to parse incoming HTTP requests and populate a Java bean
with the submitted request parameters. The Struts config file defines what 
bean class to use for a particular request. Additionally, a hook allows the 
application developer to include form validation code. The form bean is passed 
around as an attribute to the servlet request. 

FormTool provides miscellaneous methods to work with forms.

Class: org.apache.velocity.tools.struts.FormTool

Recommended name in context: $form

Methods:

public ActionForm getBean()

    Retrieve and return the form bean associated with this request. The 
    ActionForm is typically needed by view designers to populate HTML form 
    elements with values.
    Note that the form bean is available in the Velocity context by default 
    under the name defined in the Struts configuration. If the form bean
    is used repeatedly, it is recommended to create a local variable pointing
    to the bean rather than calling getBean() on each access.
    Example:
    #set ($defaults = $form.bean) 
    <input type="text" name="username" value="$defaults.username">    


public String getCancelName() 

    Retrieve and return the magic name that is to be used for cancel buttons
    in HTML forms. If this magic name is used for cancel buttons, the 
    automatic form validation is skipped if the cancel button caused the form
    submission. If automatic form validation is not used, this is irrelevant.
    

public String getToken()

    Retrieve and return the transaction control token for this session.




2) Auto-Population of the Velocity Context
------------------------------------------

VelocityViewServlet is the servlet class that is used with Struts applications
to process Velocity templates. It can be considered the equivalent of the 
JSPServlet for Velocity templates.

VelocityViewServlet automatically populates the Velocity context with several
objects that are relevant to the template designer. This includes for example
servlet request, servlet response, servlet context, etc. This section documents
all objects that are made available automatically in the Velocity context. This
is part of the view API that is available to the template designer.

Strictly speaking, auto-population of the Velocity context is not specific to 
Struts. It can be used with any servlet-based application. I describe it here, 
because Struts is the first framework that makes use of VelocityViewServlet and 
this information has not been documented anywhere yet. It will be part of a
user guide in the future.



2.1) Request, Response, Session, Servlet Context
------------------------------------------------

The following objects are added to the Velocity context:

Name            Class / Interface
--------------|----------------------------------------------------------------
$request        javax.servlet.http.HttpServletRequest

$session        javax.servlet.http.HttpSession

$response       javax.servlet.http.HttpServletResponse

$application    javax.servlet.ServletContext



2.2) Attributes of Request, Session and Servlet Context
-------------------------------------------------------

The classes HttpServletRequest, HttpSession and ServletRequest support 
attributes (see methods getAttribute(), setAttributes() of these 
classes). This allows to associated arbitrary objects with the request, 
session or servlet context. These attributes have been foreseen to provide 
the application developer a mechanism to pass information between servlets.
Struts and other web frameworks make heavy use of these attributes to
pass data from the controller to the view of an application. 

VelocityViewServlet makes all attributes of request, session and servlet
context automatically available as variables in the Velocity context. The
key of an attribute is used as the name of the variable in the Velocity 
context.
Since request attributes, session attributes and servlet context attributes 
each have their own name space, name clashes are possible. The following 
lookup priorities apply when accessing a variable:

    1) Search local Velocity context
    
    2) Search request attributes
    
    3) Search session attributes
    
    4) Search servlet context attributes
    

Example:


In Struts action class:

    ArrayList[] orders = <result of DB lookup>
    request.setAttribute("orders", orders);
    ...
    
In Velocity template:

    ## $orders is automatically available in the context
    #foreach ($o in $orders)
        $o.amount: $o.text
    #end



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





Gabriel Sidler
Software Engineer, Eivycom GmbH, Zurich, Switzerland

--
To unsubscribe, e-mail:   <ma...@jakarta.apache.org>
For additional commands, e-mail: <ma...@jakarta.apache.org>


Re: [VelTools] Velocity View API for Struts [Phase 2]

Posted by Nathan Bubna <na...@esha.com>.
Gabriel Sidler wrote:
> Nathan Bubna wrote:
> [..]
> > > Any better ideas are highly welcome.
> >
> > did you give any thought to my suggestion of renaming the context key
for
> > MessageTool instead of the one for ActionMessagesTool?  my suggestion
was to
> > change '$msg' to '$i18n' or '$text' (or something better if someone
thinks
> > of one) and to let ActionMessagesTool keep '$msgs'.
> >
> > whaddaya think?
>
> Yes, I gave it some thought. The MessageTool will easily be the most used
> context tool in any Struts application. The correspoding JSP tag is
<bean:message .../>
> In contrast, ActionMessages is new. Noboby is using it yet. So I'd rather
come up
> with some creative naming for action messages instead of for the well
established
> message resources.

good point.

> I actually begin to like your proposed $actionmsgs. Message tool ($msg)
typically
> will be used many times a page. Keeping it short is good. $actionmsgs
typically is
> used once per template. Having a slightly longer name is not an issue. The
> potential for confusion between $msg and $actionmsgs is small.

even better point.

> I propose that we go with these names for now. We can always come back and
> change later.

very true.

+1

Nathan Bubna
nathan@esha.com


--
To unsubscribe, e-mail:   <ma...@jakarta.apache.org>
For additional commands, e-mail: <ma...@jakarta.apache.org>


Re: [VelTools] Velocity View API for Struts [Phase 2]

Posted by Ted Husted <hu...@apache.org>.
The messages and errors are very closely related. The messages tag and
corresponding queue were really only invented to maintain backward
compatibility. We didn't want to change the behavior of the errors tag,
so we created another. It also gives people a way to send two streams of
application-generated messages to a page, one for errors and one for
confirmations. 

You might want to think of them as queues or batches. 

It is also important to note that the ActionMessage has been in the
nightly build for some time, and many people *are* actually using the
night build in production. 

Also, the errors and messages queues have options that associate a
particular message with a particular property, and people often use this
feature to display the error next to the property, rather than in a
lump.

-Ted.


Gabriel Sidler wrote:
> Yes, I gave it some thought. The MessageTool will easily be the most used
> context tool in any Struts application. The correspoding JSP tag is <bean:message .../>
> In contrast, ActionMessages is new. Noboby is using it yet. So I'd rather come up
> with some creative naming for action messages instead of for the well established
> message resources.
> 
> I actually begin to like your proposed $actionmsgs. Message tool ($msg) typically
> will be used many times a page. Keeping it short is good. $actionmsgs typically is
> used once per template. Having a slightly longer name is not an issue. The
> potential for confusion between $msg and $actionmsgs is small.
> 
> I propose that we go with these names for now. We can always come back and
> change later.
> 
> Gabe
> 
> >
> > Nathan Bubna
> > nathan@esha.com
> >
> > --
> > To unsubscribe, e-mail:   <ma...@jakarta.apache.org>
> > For additional commands, e-mail: <ma...@jakarta.apache.org>
> 
> --
> Gabriel Sidler
> Software Engineer, Eivycom GmbH, Zurich, Switzerland
> 
> --
> To unsubscribe, e-mail:   <ma...@jakarta.apache.org>
> For additional commands, e-mail: <ma...@jakarta.apache.org>

--
To unsubscribe, e-mail:   <ma...@jakarta.apache.org>
For additional commands, e-mail: <ma...@jakarta.apache.org>