Archive for the ‘Web programming’ Category

Shorter Grails textField

Thursday, July 24th, 2008

Making textFields in Grails is a bit verbose, at least if you want error highlighting and returned values on errors. This post shows a quick solution.

Problem

A full textField would be:

<g:textField class="${hasErrors(bean:user, field:'name', 'errors')}" value="${fieldValue(bean:user,field:'name')}" name="name"/>

Which clearly is very verbose; you have to specify “user” twice, and “name” even three times. This verbosity also makes the view less readable.

Googling for this problem resulted in: Smarter Grails Tags (a proposal). Funny that the writer exactly sees the same problem in it, also uses the “user” domain model, and also knows Stripes where you could just use something like

<stripes:text name="name"/>

and specify the bean name in the form. (Stripes has a very good Quick Start Guide, which also shows error highlighting.)

One of the less verbose proposed formats of textField is:

<g:textField bean="user" field="username" />

Implemented Solution

I found that implementing a quick version of this is surprisingly easy in Grails, it only takes for a few statements. Here is the code:

import org.codehaus.groovy.grails.plugins.web.taglib.FormTagLib

// file: project/grails-app/taglib/MyTagLib.groovy
class MyTagLib {
    // tagname "myTextField" within the "g" namespace
    def myTextField = {attrs ->
        // If a controller returned the bean, and the field has an error,
        // then "errors" will be returned as HTML class, otherwise the class will be empty.
        attrs.class = hasErrors(bean:attrs.bean, field:attrs.field, 'errors')
        // Retrieves the field value of the given bean to be rendered in the view.
        // Note: specify the bean and not the bean name. So "${user}" instead of "user"
        attrs.value = fieldValue(bean:attrs.bean, field:attrs.field)
        // Required for textField taglib. attrs.name is a keyname of the params map
        attrs.name = attrs.field
        // renders the HTML tag
        out << new FormTagLib().textField(attrs)
    }
}

Usage

<g:myTextField bean="$user" field="name" />

And ofcourse some CSS to highlight the error in a color. This can be put in the HTML head (or better, a seperate CSS file) :

<style type="text/css">
   .errors {
      background-color: red;
   }
</style>

Grails and existing Java Hibernate DAO’s

Sunday, July 20th, 2008

If you have some existing Java Hibernate entity classes (outside Grails), you only have to add one line in Datasource config, and you can use them immediately. However, if you have some exising POJO (Plain Old Java Object) Hibernate DAO’s (classes that implement a Data Access Object pattern), you’ll have to do some additional steps to make it a bit suitable.

(The solution described in this post can also be handy when you need data access on places where GORM is NOT available. GORM not available? Yes, GORM is not fully available when you access collections via a taglib that is accessed via a Sitemesh layout. (A scenerio that isn’t rare.) (Should be considered as a bug?) In that case you will get a lazily initialize a collection error. If you use HibernateUtil, you can get around this by just opening new session yourself.)

Existing Hibernate entities and GORM

You can use existing Hibernate Java entities directly in Grails. The only thing that you’ll have to configure is:

  1. define mappings in hibernate.cfg.xml
  2. set GrailsAnnotationConfiguration as configClass in DataSource.groovy

For example:
webapp/grails-app/conf/hibernate/hibernate.cfg.xml :

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
		"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
		"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <mapping class="myPackage.Product"/>
        <mapping class="myPackage.Customer"/>
        <mapping class="myPackage.Supplier"/>
    </session-factory>
</hibernate-configuration>

webapp/grails-app/conf/DataSource.groovy :

import org.codehaus.groovy.grails.orm.hibernate.cfg.GrailsAnnotationConfiguration

dataSource {
    configClass = GrailsAnnotationConfiguration.class
    pooled = true
    driverClassName = "com.mysql.jdbc.Driver"
    url = "jdbc:mysql://localhost/mydb"
    username = "myusername"
    password = "mypass"
    dbCreate = "create" // one of 'create', 'create-drop','update'
    dialect= org.hibernate.dialect.MySQLInnoDBDialect
}
hibernate {
    cache.use_second_level_cache=true
    cache.use_query_cache=true
    cache.provider_class='com.opensymphony.oscache.hibernate.OSCacheProvider'
}

Now you can put your existing Hibernate java entities in webapp/src/entities (or any other package), and they will work immediately and have GORM functionality.
For example, in the Grails controller classes, you can direcly use Product.get(100) (to get a Product instance that has id 100). Hibernate sessions and transactions are created/invoked automatically.

Exising Hibernate DAO’s

If you don’t need any GORM functionality and you don’t want Grails to touch sessions, then you can use your existing unaltered full hibernate.cfg.xml.

However, if you have some POJO DAO’s that use the HibernateUtil helperclass, you will have to do some additional steps to make it a bit suitable. (In this example, I use the configurations above.)

By default Grails injects a SessionFactory
First, your DAO’s will need a HibernateSession to perform work. By default Grails injects a SessionFactory into Grails controllers that have a “sessionFactory” variable defined. So the following controller will automatically have a SessionFactory available:

import org.hibernate.*;

class ProductController {
    // This one will be injected
    SessionFactory sessionFactory

    def index = {
        Session session = sessionFactory.getCurrentSession()
        println session.createQuery("from Product").list()
    }
}

(You can also use Gorm in this controller example and don’t use the SessionFactory yourself, but this just to show that a SessionFactory will be injected.)

HibernateUtil used by the DAO’s
In the example, the DAO’s use HibernateUtil to get a SessionFactory. By default HibernateUtil create a SessionFactory itself, but the SessionFactory provided by Grails is needed instead, so we alter HibernateUtil slightly:

package persistence;

import org.hibernate.*;

public class HibernateUtil {
    private static SessionFactory sessionFactory;

    public static SessionFactory getSessionFactory() { return sessionFactory; }
    public static void setSessionFactory(SessionFactory sf) { sessionFactory = sf; }

    public static void shutdown() { sessionFactory.close(); }
}

Set SessionFactory for HibernateUtil
We want HibernatUtil to be ready with a SessionFactory after booting, so we configure HibernateUtil during the bootstap. We alter webapp/grails-app/conf/BootStrap.groovy to:

import persistence.HibernateUtil
import org.springframework.web.context.support.WebApplicationContextUtils

class BootStrap {

     def init = { servletContext ->
        def ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext)
        def sf  = ctx.getBean('sessionFactory')
        HibernateUtil.setSessionFactory(sf)
     }

     def destroy = {
         HibernateUtil.shutdown()
     }
}

Now the DAO’s can use HibernateUtil.getSessionFactory().getCurrentSession() to get a HibernateSession.

Struts2 table annoyance

Saturday, July 5th, 2008

I was trying out a bit of Struts 2 just to test it out. An annoyance that quickly came up is that the HTML layout of forms are all table based. For example, if you want an input field for your name, then a column-based HTML table will be created automatically for that. The first column contains a HTML label, and the second the input field.

For example, the following Struts2 code:

<s:form action="HelloWorld">
    		<s:textfield name="name" label="Your name"/>
    		<s:submit/>
		</s:form>

will yield this HTML code:

<form id="HelloWorld" name="HelloWorld" onsubmit="return true;" action="/StrutsInAction/chapterTwo/HelloWorld.action" method="post">
	<table class="wwFormTable">
		<tr>
			<td class="tdLabel"><label for="HelloWorld_name" class="label">Your name:</label></td>
			<td><input type="text" name="name" value="" id="HelloWorld_name"/></td>
		</tr>
   		<tr>
			<td colspan="2"><div align="right"><input type="submit" id="HelloWorld_0" value="Submit"/></div></td>
		</tr>
	</table>
</form>

What if you want to work without HTML tables? Or what if you want to put a label on the first row and its input field on the second row, instead of using two columns? You can by using the “simple” theme instead of the default “xhtml” theme. Set it using:

<s:form action="HelloWorld" theme="simple">

The generated HTML code will now be:

<form id="HelloWorld" name="HelloWorld" onsubmit="return true;" action="/StrutsInAction/chapterTwo/HelloWorld.action" method="post">
	<input type="text" name="name" value="" id="HelloWorld_name"/>
	<input type="submit" id="HelloWorld_0" value="Submit"/>
</form>

But…. using the simple theme, will drop validation, error reporting, ajax etc……

So if you don’t want those column based HTML tables but do want the default framework functionality (validation etc), you will have to make your own themes……

JSF doesn’t have this problem, there you could just write something like:

<h:form>
	<h:outputLabel for="name">Your name:</h:outputLabel>
	<h:inputText value="#{formAction.name}"/>

This is a bit more coding then using Struts 2, but it gives you the flexibility to place the outputLabel wherever you want, instead of being locked to two HTML columns.

More info:
http://struts.apache.org/2.x/docs/themes-and-templates.html
http://www.vitarara.org/cms/struts_2_cookbook/creating_a_theme

Seam-gen and default ROOT context

Monday, June 30th, 2008

If you are using seam-gen to deploy webapps as war-files to a webserver (for example JBoss AS), the root url of your webapp will be something like http://example.com/myproject/. (Where “myproject” is the name that you gave to your webapps when setting it up using seam-gen.) If you want your webapp to be assigned to the root (http://example.com/) (also known as the default ROOT context), then read on.

To change the root context, I perform the following steps. Note, there might be a better way, but this one works for me. If you’re using ejb instead of war, then you probably have to do some additional steps.

Tested using jboss-4.2.2.GA and jboss-seam-2.0.2.SP1.

1) After creating the project, open build.xml. Change

<property name="war.dir" value="exploded-archives/${project.name}.war" />

to

<property name="war.dir" value="exploded-archives/ROOT.war" />

and change

<property name="war.deploy.dir" value="${deploy.dir}/${project.name}.war" />

to

<property name="war.deploy.dir" value="${deploy.dir}/ROOT.war" />

2) Go to the following directory: {your.jboss.home.dir}\server\default\deploy\jboss-web.deployer. And rename ROOT.war to something else. The JBoss manager might then not be available anymore.

3) Now run an explode, and your webapp will be at the ROOT context.

JSF doesn’t validate empty forms

Thursday, June 19th, 2008

Error:

Caused by org.hibernate.validator.InvalidStateException with message: “validation failed for: MyHibernateEntity”

Are you getting this error while trying to validate a form with empty fields using Seam, JSF and Hibernate? Then read on.

Seam allows you to define validation conditions on a single place: on the Hibernate / JPA entities. And then use this condition in the view without duplicating them.
Sounds nice, but when you try it in practice, you can easily run into the “validation failed” error above.

The problem is caused by JSF. It sounds idiot (and it is), but JSF validators aren’t invoked on empty fields. So the following code already causes the error when submitting an empty comment field

<h:inputTextarea id="comment" value="#{user.comment}" cols="10" rows="3">
   <s:validate/>
</h:inputTextarea>
<h:message for="comment" />
@Entity
public class User {
  // ....

  @NotNull
  private String comment;

  // ....
}

Fortunately a solution is simple, set the required attribute of the input field element to true. Like this:

<h:inputTextarea id="comment" value="#{user.comment}" cols="10" rows="3" required="true">

More info:
http://jamiemcilroy.wordpress.com/2006/10/10/not-quite-what-i-expectedjsf-validation/
http://forum.java.sun.com/thread.jspa?threadID=5055877
http://www.jboss.com/index.html?module=bb&op=viewtopic&t=127793

Seam and URL rewriting with parameters and forms

Monday, June 16th, 2008

Making pretty bookmarkable RESTful URLs in JSF is hard. Fortunately the Seam framework solves this problem by supporting HTTP parameters, advanced page navigation, and can use the help of UrlRewriteFilter. But making bookmarkable parameter URLs in combination with a POST form can still be a bit tricky. This blog post shows an example how to solve this problem.

Note: The code snippets used are only fragments. I also assume that UrlRewriteFilter is already installed etc. Seam-gen also contains UrlRewriteFilter, but you might have to add it to the deployment and configure web.xml. Use /rewrite-status to see if it’s working.

Example

We have a website that shows products of a given catagory. In our case, we use the catagory ‘audio’. We want bookmarkable URLs, like http://example.com/products.jsf?catagory=audio instead of http://example.com/products.jsf. And we want pretty URLs that hide technology implementation and parameter names, so in the end we want only URLs like http://example.com/products/audio.

Also we want a HTML POST form on the page that allows us to add products to a catagory (’audio’ in this case). After submitting this form, we want the URLs to still be pretty, so also here we only want URLs like /products/audio.

Making bookmarkable URLs for first HTTP requests

A URL is bookmarkable when the URL by itself contains all parameters needed to retrieve the page, like
/products.jsf?catagory=audio.

JSF is unable to do this because it cannot handle URL parameters. JSF depends on a HTTP POST (the postback request) to retrieve the page, so the user first has to click a button, after which JSF will show the page with audio products.
The Seam framework solves this problem by handling URL parameters, so we use Seam. (This is just one reason to use Seam around JSF. There are many more.)

Because we are using Seam around JSF, the URL becomes /products.seam?catagory=audio.
To make these parameters, we add the following to pages.xml:

<page view-id="/products.seam">
    <param name="catagory" value="#{productsManager.catagory}" />
</page>

In the code above, productsManager is a backingbean and catagory is a property that will be set to ‘audio’ automatically when the url /products.seam?catagory=audio is requested.

Making pretty URLs for first HTTP requests

After enabling parameters for our URLs, we want them to be pretty. We want /products/audio instead of /products.seam?catagory=audio.
This is done by using UrlRewriteFilter. We add the following code to urlrewrite.xml:

<rule>
    <from>/products/(.*)</from>
    <to>/products.seam?catagory=$1</to>
</rule>

Bookmarkable URLs after a form submit

By default, with the code used above, when we use the form at /products/audio to add a product the catagory ‘audio’, the form will send us to the URL /products.seam without parameters, which is not bookmarkable! To make it bookmarkable, change the code that we have added to pages.xml to:

<page view-id="/products.seam">
    <param name="catagory" value="#{productsManager.catagory}" />
    <navigation from-action="#{productsManager.addProduct}">
        <redirect view-id="/products.seam"/>
    </navigation>
</page>

Where addProduct is an action method bound to the h:commandButton of the form.

When the form is now submitted, the user will be redirected to /products.seam?catagory=audio&cid=1, which is bookmarkable.
Notice that a cid parameter is added by Seam, which Seam uses to track conversations. (To remove it, read further.)

Pretty URLs after a form submit

After submitting the form, we have /products.seam?catagory=audio&cid=1. To make it pretty again (/products/audio), we use outbound urlrewriting. Add the following code to urlrewrite.xml:

<outbound-rule>
    <from>^/products.seam\?catagory=(.*)</from>
    <to>/products/$1</to>
</outbound-rule>

After a form submit, the URL will now be: /products/audio?cid=1. The URL is now prettier, but not completely, we still have the cid parameter. If you don’t need to maintain conversations, the cid parameter can be removed with by changing the outbound rule to:

<outbound-rule>
    <from>^/products.seam\?catagory=(\w*)&amp;cid=\d*</from>
    <to>/products/$1</to>
</outbound-rule>

Disadvantage of the solution

1) Extra delay:
If you would make a HTML form without JSF, you could immediately specify the action URL (attribute of the HTML form), so you could immediately specify to URL you want to send form data to, without all the rewriting. When the browser then submits the POST data (immediately to the pretty bookmarkable URL), the server will immediately return the page with results. So only one HTTP request/response is needed. But with Seam/JSF two request/reponses are needed if you want pretty bookmarkable URLs, which is an extra unwanted delay, just to get the job done in these frameworks.

The following steps happen in the background in our example:

  1. The user enters /products/audio in the browser.
  2. The server responds with the page containing a HTML form like: <form method="post" action="/products.seam">. Notice that it refers to /products.seam without parameters.
  3. The user enters form data and submits it. The browser will generate a HTTP POST request to /products.seam.
  4. The server processes the form data using productsManager.addProduct(), and responds with a HTTP REDIRECT to /products/audio. (A HTTP redirect doesn’t contain a page.)
  5. The browser receives the redirect, and immediately requests for /products/audio, using a HTTP GET.
  6. The server receives the HTTP GET and gives a HTTP OK reponse containing the page the user already was on.

Without the Seam/JSF framework, these steps would be shorter and faster, saving an extra client-server-client roundtrip. Because you could then specify the URL to submit to in the HTML form, and thus won’t need the HTTP redirect. But these extra step can also be used as an advantage; it allow serversided navigation rules. But it would be nice if both options were possible, allowing the developer to choose.

2) SEO:
Google recently announced that they are going to crawl through HTML forms to find URLs.
Because the HTML form is using /products.seam in the HTML code instead of the pretty bookmarkable url, Google might index URLs you don’t want to be indexed. (This can be stopped using robots.txt, but other crawler maybe might not use that file.) 

3) Doesn’t work for validation:
When a form is not validated because the form fields are not passing the specified field conditions, the JSF life cycle will end and thus skip the Invoke Application phase, and thus the navigation rules above will not be executed. I don’t know if there’s an easy solution for this.

Notes:

1)
When using UrlRewriteFilter, make sure you encode XML entities, so a & becomes & in urls that have a querystring.

2)
The querystring of an URL is everything behind the questionmark, like /products.seam?catagory=audio&login=true. In UrlRewriteFilter, like in mod_rewrite, querystrings are handled separatly from the URL. In UrlRewriteFilter you’ll have to use the <condition> element when using a <rule> element for an URL containing a querystring. For example:

<rule>
<condition type="query-string">catagory=(\w*)&amp;login=true</condition>
<from>/products.seam</from>
<to type="redirect">/products/%1</to>
</rule>

Also note that you’ll have to use %1 instead of $1 when using conditions.
You don’t have to use the <condition> element when using querystrings with the <outbound-rule> element.