Server-Side Code Generation - Ajax Patterns

Server-Side Code Generation

From Ajax Patterns

(Difference between revisions)
Revision as of 01:17, 16 September 2005
Mahemoff (Talk | contribs)
Full Text
← Previous diff
Current revision
164.67.235.200 (Talk | contribs)

Line 40: Line 40:
<span class="solution">Automatically generate HTML and Javascript from server-side code.</span> You write code in a standard server-side language like Java, or a custom language like that used in Backbase, and it's converted to HTML and Javascript. Depending on the framework, you might not need to code directly in HTML or Javascript at all. Since you're unlikely to create such a framework yourself, this pattern relies on a certain category of publicly availably [http://ajaxpatterns.org/Ajax_Frameworks Ajax Framework]. <span class="solution">Automatically generate HTML and Javascript from server-side code.</span> You write code in a standard server-side language like Java, or a custom language like that used in Backbase, and it's converted to HTML and Javascript. Depending on the framework, you might not need to code directly in HTML or Javascript at all. Since you're unlikely to create such a framework yourself, this pattern relies on a certain category of publicly availably [http://ajaxpatterns.org/Ajax_Frameworks Ajax Framework].
-In the case of all code being autogenerated, the code is something like a conventional deskto application. Widgets and event-handler are defined, and the browser generates the appropriate HTML, along with [[XMLHttpRequest Calls]] and general Javascript handling. As well, the framework will often generate [[Ajax Stub]]s to deal with incoming calls and pass them to appropriate application code.+In the case of all code being autogenerated, the code is something like a conventional desktop application. Widgets and event-handler are defined, and the browser generates the appropriate HTML, along with [[XMLHttpRequest Calls]] and general Javascript handling. As well, the framework will often generate [[Ajax Stub]]s to deal with incoming calls and pass them to appropriate application code.
In other frameworks, the approach is more mixed. The framework might let you create a [[Slider]] with just a single tag, for example. But in the tag, you'll specify a Javascript function to be called whenever the slider value changes. In other frameworks, the approach is more mixed. The framework might let you create a [[Slider]] with just a single tag, for example. But in the tag, you'll specify a Javascript function to be called whenever the slider value changes.
There are several arguments for [[Server-Side Code Generation]]: There are several arguments for [[Server-Side Code Generation]]:
-+ Developers don't have to know HTML and Javascript. One nasty thing about the web paradigm is that developers usually have to learn HTML, CSS, and Javascript on top of any server-side languages. Along with the raw language, each of these languages has its own conventions, patterns, and libraries to get familiar with. It's not surprising that few people master both sides. [[Server-Side Code Generation]] allows developers to focus their attention only on the server-side language.+* Developers don't have to know HTML and Javascript. One nasty thing about the web paradigm is that developers usually have to learn HTML, CSS, and Javascript on top of any server-side languages. Along with the raw language, each of these languages has its own conventions, patterns, and libraries to get familiar with. It's not surprising that few people master both sides. [[Server-Side Code Generation]] allows developers to focus their attention only on the server-side language.
-+ The framework can, in theory, handle graceful degradation transparently. In other words, it can free the developer of worrying about browser portability, Javascript or cookies being turned off, or [[XMLHttpRequest Call]]s timing out.+* The framework can, in theory, handle graceful degradation transparently. In other words, it can free the developer of worrying about browser portability, Javascript or cookies being turned off, or [[XMLHttpRequest Call]]s timing out.
-+ The framework can, in theory, deliver multiple platforms simultaneously. A single code base can be used to generate a web application (Ajaxian or not), standalone desktop application, and maybe even a mobile application.+* The framework can, in theory, deliver multiple platforms simultaneously. A single code base can be used to generate a web application (Ajaxian or not), standalone desktop application, and maybe even a mobile application.
-However, code generation does comes at a cost to usability. Look at it this way: anything you could generate from the server, a skilled developer could also hand-code. The reverse is not true; given enough time and talent, it's always possible to build a custom solution that's superior in terms of usability. So, to be worthwhile, the framework must add enough value in terms of productivity and support for non-experts, to be compensate for the drop in usability. Whether this can be achieved really depends on two things: how much users will gain from a custom-built application; and how much of a boost the framework will give you. On the second point, consider a few counter-arguments to the benefits above:+However, code generation does comes at a cost to usability. Look at it this way: anything you could generate from the server, a skilled developer could also hand-code. The reverse is not true; given enough time and talent, it's always possible to build a custom solution that's superior in terms of usability. So, to be worthwhile, the framework must add enough value in terms of productivity and support for non-experts, to compensate for the drop in usability. Whether this can be achieved really depends on two things: how much users will gain from a custom-built application; and how much of a boost the framework will give you. On the second point, consider a few counter-arguments to the benefits above:
-+ The first point, about developer's not having to learn HTML and Javascript, has traditionally been the most compelling. Server-side developers have produced minimal '''satisficing''', rather than '''optimal''', interfaces, allowing them to focus on the server side. It's not uncommon to see advice against anything relatively complex being performed on the server-side. But as Ajax becomes more prominent, this argument becomes less compelling. As discussed in [[Fat Client]], Javascript is undergoing a renaissance - developers will learn about it, tools and libraries will evolve, patterns will emerge. All of this reduces the argument for isolating developers from HTML and Javascript.+* The first point, about developer's not having to learn HTML and Javascript, has traditionally been the most compelling. Server-side developers have produced minimal '''satisficing''', rather than '''optimal''', interfaces, allowing them to focus on the server side. It's not uncommon to see advice against anything relatively complex being performed on the server-side. But as Ajax becomes more prominent, this argument becomes less compelling. As discussed in [[Fat Client]], Javascript is undergoing a renaissance - developers will learn about it, tools and libraries will evolve, patterns will emerge. All of this reduces the argument for isolating developers from HTML and Javascript.
-+ A server-side framework may well be able to handle graceful degradation and browser versions transparently. But to the extent that's possible, a browser script can also achieve the same effect, as discussed in [[Cross-Browser Component]].+* A server-side framework may well be able to handle graceful degradation and browser versions transparently. But to the extent that's possible, a browser script can also achieve the same effect, as discussed in [[Cross-Browser Component]].
-+ The dream of transforming a single code into a variety of different user-interface styles has been around for a while. Certainly, many modern UI toolkits are cross-platform, running on different operating systems from the same code base. However, can a single code base lead to both a web application and a desktop application? It's possible in theory and in proof-of-concept demos. But, in practice, users expect applications to follow the conventions of the platform and that's difficult to achieve with a single generation. It might, however, work if the framework allows for platform-specific tailoring.+* The dream of transforming a single code into a variety of different user-interface styles has been around for a while. Certainly, many modern UI toolkits are cross-platform, running on different operating systems from the same code base. However, can a single code base lead to both a web application and a desktop application? It's possible in theory and in proof-of-concept demos. But, in practice, users expect applications to follow the conventions of the platform and that's difficult to achieve with a single generation. It might, however, work if the framework allows for platform-specific tailoring.
-I expect the full-featured frameworks to become particularly prominent on intranet applications, where new functionality is often more critical than usability, and users can be trained to work around problems. Hand-coded HTML and Javascript is more likely for public dot-coms where alternatives are abundant and the pressure of competition means its critical to optimise the user-interface. In those environments, there is still some role for Server-Side Code Generation, but mainly as a helper for very specific tasks and with some flexibility, rather than as the overarching architectural style.+Full-featured frameworks will likely be more prominent on intranet applications, where new functionality is often more critical than usability, and users can be trained to work around problems. Hand-coded HTML and Javascript is more likely for public dot-coms where alternatives are abundant and the pressure of competition means its critical to optimise the user-interface. In those environments, there is still some role for Server-Side Code Generation, but mainly as a helper for very specific tasks and with some flexibility, rather than as the overarching architectural style.
<!-- =================================================================== --> <!-- =================================================================== -->
Line 69: Line 69:
[http://www.nextapp.com/products/echo2/ Echo2] is an open-source framework by NextApp, which takes the "whole hog" approach and generates '''all''' HTML and Javascript from Java source code. [http://demo.nextapp.com/InteractiveTest/ia An online demo] shows how Echo2's user-interface widget classes manifest themselves in the browser. [http://www.nextapp.com/products/echo2/ Echo2] is an open-source framework by NextApp, which takes the "whole hog" approach and generates '''all''' HTML and Javascript from Java source code. [http://demo.nextapp.com/InteractiveTest/ia An online demo] shows how Echo2's user-interface widget classes manifest themselves in the browser.
 +
 +== Pioneer-soft's Ajax GUI-API ==
 +
 +[http://cbsdf.com/developer-guide.htm Pioneer-soft’s Ajax reusable GUI Classes] are based on innovative “patent pending” processes that takes a very [http://www.cbsdf.com/technologies/DHTML-Widgets/Widget-samples.htm simple approach/pattern]. The [http://cbsdf.com/technologies/DHTML-Widgets/TECH-Summary.htm technology] let developers create custom reusable Ajax GUI Classes. Once created, the GUI Classes may be used to build complex [http://cbsdf.com/misc_docs/gui-api-brief.htm graphics intensive Ajax applications] such as real-time simulations or games, which are more complex than possible on traditional desktop GUI platforms. The technology at the moment targeted at emerging [http://cbsdf.com/misc_docs/choose-complete-solution.htm Vector graphics] technologies (e.g. XUL+SVG, XAML/WPF/E or MXML/Flash), but can also be used to build XHTML/DHTML applications.
 +
 +* Newbie introduction to emerging Vector Graphics: [http://cbsdf.com/Newbies/Flight-main.htm Very Basic Tutorial for Developing a GUI Widget for GIS]
== Ruby on Rails == == Ruby on Rails ==
Line 78: Line 84:
:url =>{ :action => :say_when }) %> :url =>{ :action => :say_when }) %>
-== BackBase ==+== Backbase ==
-[http://backbase.com/ BackBase] is a commercial framework that extends standard XHTML with Backbase-specific tags. A Backbase server-side framework mediates between the browser and the Backbase code. Many of the XML tags specify Ajaxian actions and widgets, such as <pre><tt><b:drag></tt></pre> for [[Drag-And-Drop]] and <pre><tt><s:fxstyle</tt></pre> for various visual effects. There are several [http://www.backbase.com/#dev/tech/index.xml[3] innovative demos available from the homepage].+[http://backbase.com/ Backbase] is a commercial framework that extends standard XHTML with Backbase-specific tags. A Backbase server-side framework mediates between the browser and the Backbase code. Many of the XML tags specify Ajaxian actions and widgets, such as <pre><tt><b:drag></tt></pre> for [[Drag-And-Drop]] and <pre><tt><s:fxstyle</tt></pre> for various visual effects. There are several [http://www.backbase.com/#dev/tech/index.xml\[3\] innovative demos available from the homepage.
== AjaxTags == == AjaxTags ==
-[http://ajaxtags.sourceforge.net/ AjaxTags] is a collection of JSP tags to ease development of Ajax interaction. There's an <pre><tt><autocomplete></tt></pre> tag for [[Suggestion]] and an <pre><tt><ajax:update</tt></pre> field to perform a [[Display Morphing]] with the response of an [[XMLHttpRequest]].+[http://ajaxtags.sourceforge.net/ AjaxTags] is a collection of JSP tags to ease development of Ajax interaction. There's an <pre><tt><autocomplete></tt></pre> tag for [[Suggestion]] and an <pre><tt><ajax:update</tt></pre> field to perform a [[Display Morphing]] with the response of an [[XMLHttpRequest Call]].
== Comfort.ASP == == Comfort.ASP ==
Line 146: Line 152:
In a manner almost identical to a swing application, the GamePane is built up by adding sub-elements and registering events. It acts as an <tt>ActionListener</tt> for the buttons it contains, hence there's an <tt>actionPerformed</tt> event, which encapsulates the guess evaluation logic. In a manner almost identical to a swing application, the GamePane is built up by adding sub-elements and registering events. It acts as an <tt>ActionListener</tt> for the buttons it contains, hence there's an <tt>actionPerformed</tt> event, which encapsulates the guess evaluation logic.
 + import java.util.Random;
class GamePane extends ContentPane implements ActionListener { class GamePane extends ContentPane implements ActionListener {
- + private static final Random rand = new Random();
- private int randomNumber = ((int) Math.floor(Math.random() * 100)) + 1;+ private int randomNumber = rand.nextInt(100) + 1;
private int lowerBound = 1; private int lowerBound = 1;
private int upperBound = 100; private int upperBound = 100;

Current revision

Evidence: 2/3

Tags: AutoGenerated CodeGen Framework Library

Orientation: ServerCentric


Contents

In A Blink

Diagram Source code transformed to HTML/JS


Technical Story

Dave's creating a web application with a trendy new server-side framework, ZeroWeb. The framework lets him write everything in Java as if he's writing a standalone GUI application. It's capable of using that code to generate a conventional edition of the application, An Ajaxian edition, a desktop edition, and - for an extra $99.95 - a smartphone app too.


Problem

How do you avoid using HTML and Javascript?


Forces

  • HTML and Javascript are the only code recognised by standard browser - any Ajaxian application must be represented in a combination of these formats.
  • Ajax is increasing the complexity of HTML and Javascript. Whereas Javascript was previously used for simple tasks like navigation support or form validation, it's now driving the interaction in many applications.
  • Most Ajaxian applications also have a substantial back-end, which is rarely implemented in Javascript.
  • It's difficult to completely separate the roles of browser-side developer and server-side developer. In fact, it's often more desirable to have the same developer working on a vertical slice of functionality, i.e. contributing a little to all tiers in order to deliver a new requirement. Thus, the same developer is often expected to work across tiers, where the environment differs significantly.
  • Server-side development has certain advantages over Javascript development. In some cases, there's better support for code editing, refactoring, testing, and so on.
  • Sometimes, you want different user-interfaces for the same application - a non-Ajaxian version or a desktop version, for example.


Solution

Automatically generate HTML and Javascript from server-side code. You write code in a standard server-side language like Java, or a custom language like that used in Backbase, and it's converted to HTML and Javascript. Depending on the framework, you might not need to code directly in HTML or Javascript at all. Since you're unlikely to create such a framework yourself, this pattern relies on a certain category of publicly availably Ajax Framework.

In the case of all code being autogenerated, the code is something like a conventional desktop application. Widgets and event-handler are defined, and the browser generates the appropriate HTML, along with XMLHttpRequest Calls and general Javascript handling. As well, the framework will often generate Ajax Stubs to deal with incoming calls and pass them to appropriate application code.

In other frameworks, the approach is more mixed. The framework might let you create a Slider with just a single tag, for example. But in the tag, you'll specify a Javascript function to be called whenever the slider value changes.

There are several arguments for Server-Side Code Generation:

  • Developers don't have to know HTML and Javascript. One nasty thing about the web paradigm is that developers usually have to learn HTML, CSS, and Javascript on top of any server-side languages. Along with the raw language, each of these languages has its own conventions, patterns, and libraries to get familiar with. It's not surprising that few people master both sides. Server-Side Code Generation allows developers to focus their attention only on the server-side language.
  • The framework can, in theory, handle graceful degradation transparently. In other words, it can free the developer of worrying about browser portability, Javascript or cookies being turned off, or XMLHttpRequest Calls timing out.
  • The framework can, in theory, deliver multiple platforms simultaneously. A single code base can be used to generate a web application (Ajaxian or not), standalone desktop application, and maybe even a mobile application.

However, code generation does comes at a cost to usability. Look at it this way: anything you could generate from the server, a skilled developer could also hand-code. The reverse is not true; given enough time and talent, it's always possible to build a custom solution that's superior in terms of usability. So, to be worthwhile, the framework must add enough value in terms of productivity and support for non-experts, to compensate for the drop in usability. Whether this can be achieved really depends on two things: how much users will gain from a custom-built application; and how much of a boost the framework will give you. On the second point, consider a few counter-arguments to the benefits above:

  • The first point, about developer's not having to learn HTML and Javascript, has traditionally been the most compelling. Server-side developers have produced minimal satisficing, rather than optimal, interfaces, allowing them to focus on the server side. It's not uncommon to see advice against anything relatively complex being performed on the server-side. But as Ajax becomes more prominent, this argument becomes less compelling. As discussed in Fat Client, Javascript is undergoing a renaissance - developers will learn about it, tools and libraries will evolve, patterns will emerge. All of this reduces the argument for isolating developers from HTML and Javascript.
  • A server-side framework may well be able to handle graceful degradation and browser versions transparently. But to the extent that's possible, a browser script can also achieve the same effect, as discussed in Cross-Browser Component.
  • The dream of transforming a single code into a variety of different user-interface styles has been around for a while. Certainly, many modern UI toolkits are cross-platform, running on different operating systems from the same code base. However, can a single code base lead to both a web application and a desktop application? It's possible in theory and in proof-of-concept demos. But, in practice, users expect applications to follow the conventions of the platform and that's difficult to achieve with a single generation. It might, however, work if the framework allows for platform-specific tailoring.

Full-featured frameworks will likely be more prominent on intranet applications, where new functionality is often more critical than usability, and users can be trained to work around problems. Hand-coded HTML and Javascript is more likely for public dot-coms where alternatives are abundant and the pressure of competition means its critical to optimise the user-interface. In those environments, there is still some role for Server-Side Code Generation, but mainly as a helper for very specific tasks and with some flexibility, rather than as the overarching architectural style.


Decisions


Real-World Examples

These examples describe frameworks that support this pattern, and in different ways.

Echo2

Echo2 is an open-source framework by NextApp, which takes the "whole hog" approach and generates all HTML and Javascript from Java source code. An online demo shows how Echo2's user-interface widget classes manifest themselves in the browser.

Pioneer-soft's Ajax GUI-API

Pioneer-soft’s Ajax reusable GUI Classes are based on innovative “patent pending” processes that takes a very simple approach/pattern. The technology let developers create custom reusable Ajax GUI Classes. Once created, the GUI Classes may be used to build complex graphics intensive Ajax applications such as real-time simulations or games, which are more complex than possible on traditional desktop GUI platforms. The technology at the moment targeted at emerging Vector graphics technologies (e.g. XUL+SVG, XAML/WPF/E or MXML/Flash), but can also be used to build XHTML/DHTML applications.

Ruby on Rails

Ruby On Rails is a web framework which embeds Ruby inside web pages. That in itself is not new, but Rails offer helpers which are Ruby classes that are embedded to speed up page construction. For example, you can issue an XMLHttpRequest Call followed by a Display Morphing, using the following embedded Ruby call.

 <%= link_to_remote( "click here",
                  :update => "time_div",
                  :url =>{ :action => :say_when }) %>

Backbase

Backbase is a commercial framework that extends standard XHTML with Backbase-specific tags. A Backbase server-side framework mediates between the browser and the Backbase code. Many of the XML tags specify Ajaxian actions and widgets, such as
<tt><b:drag></tt>
for Drag-And-Drop and
<tt><s:fxstyle</tt>
for various visual effects. There are several [1] innovative demos available from the homepage.

AjaxTags

AjaxTags is a collection of JSP tags to ease development of Ajax interaction. There's an
<tt><autocomplete></tt>
tag for Suggestion and an
<tt><ajax:update</tt>
field to perform a Display Morphing with the response of an XMLHttpRequest Call.

Comfort.ASP

Comfort.ASP takes an unusual approach. It automatically adds Web Remoting to a conventional, non-Ajax application. By instrumenting the HTML, the framework can intercept standard form submissions and transform them into XMLHttpRequest Calls. By monitoring server output, Comfort's server-side script can respond to these calls by sending back only "deltas" - the difference between the current HTML and the desired HTML. Think of it as an analogy to movie file formats, which describe each frame by stating how the last frame must be altered.


Code Examples

Echo2 Number Guess

Echo2 provides full source for a tutorial application, Number Guess. User guesses a number between 1 and 100, the application tells them if it's higher or lower, user tries again, hilarity ensues. Note that the demo isn't running online.

An Echo2 application is run as a Java servlet extending Echo2's WebContainerServlet. The superclass takes care of most interaction; the concrete servlet must do just one thing: declare an ApplicationInstance</a>. In Echo2, an <tt>ApplicationInstance object is the application state for a given user.

 /**
  * Guess-a-number Tutorial Application Servlet Implementation.
  */
 public class NumberGuessServlet extends WebContainerServlet {

     /**
      * @see nextapp.echo2.webcontainer.WebContainerServlet#newApplicationInstance()
      */
     public ApplicationInstance newApplicationInstance() {
         return new NumberGuessApp();
     }
 }

The main application object simply initialises a new window and controls two top-level user-interface elements. Specifically, it adds a GamePane on startup, which is where the main action takes place, and a CongratulationsPane upon victory. (All comments ommitted.)

 public class NumberGuessApp extends ApplicationInstance {

     private Window mainWindow;

     public Window init() {
         mainWindow = new Window();
         mainWindow.setTitle("Echo2 Guess-A-Number");
         startNewGame();
         return mainWindow;
     }

     void startNewGame() {
         ...
         mainWindow.setContent(new GamePane());
     }
     void congratulate(int numberOfTries) {
         mainWindow.setContent(new CongratulationsPane(numberOfTries));
     }

 }

 class GamePane extends ContentPane implements ActionListener {
   ...
 }

 class CongratulationsPane extends ContentPane implements ActionListener {
   ...
 }

In a manner almost identical to a swing application, the GamePane is built up by adding sub-elements and registering events. It acts as an ActionListener for the buttons it contains, hence there's an actionPerformed event, which encapsulates the guess evaluation logic.

 import java.util.Random;
 class GamePane extends ContentPane implements ActionListener {
     private static final Random rand = new Random();
     private int randomNumber = rand.nextInt(100) + 1;
     private int lowerBound = 1;
     private int upperBound = 100;
     private int numberOfTries = 0;
     private TextField guessEntryField;
     private Label statusLabel = new Label();
     private Label countLabel = new Label("You have made no guesses.");
     private Label promptLabel= new Label("Guess a number between 1 and 100: ");
     private int guess;

     GamePane() {
         super();

         Column layoutColumn = new Column();
         layoutColumn.setCellSpacing(new Extent(10));
         add(layoutColumn);
         ...
         Button submitButton = new Button("Submit Your Guess");
         submitButton.setActionCommand("submit guess");
         submitButton.setForeground(Color.BLACK);
         submitButton.setBackground(Color.GREEN);
         submitButton.setWidth(new Extent(200));
         submitButton.addActionListener(this);
         layoutColumn.add(submitButton);
     }

     public void actionPerformed(ActionEvent e) {
         if (e.getActionCommand().equals("new game")) {
             ((NumberGuessApp) ApplicationInstance.getActive()).startNewGame();
         } else if (e.getActionCommand().equals("submit guess")) {
             ++numberOfTries;
             ...
             if (guess == randomNumber) {
                 ((NumberGuessApp) ApplicationInstance.getActive()).congratulate(numberOfTries);
             } else if (guess < 1 || guess > 100) {
                 statusLabel.setText("Your guess, " + guess  + " was not between 1 and 100.");
             } else if (guess < randomNumber) {
               ...
             }
             ...
         }
     }
 }


Alternatives

Browser-Side Templating

Browser-side templating is a form of "Client-Side Code Generation", an alternative to Server-Side Code Generation.


Related Patterns

HTML Response

Server-side code generation produces HTML responses, so is technically one form of HTML Response. It's also a form of "Javascript Response", the variant described in On-Demand Javascript. However, the emphasis in those patterns is on directly created HTML and Javascript, rather than delegation to a generation framework.


Want to Know More?