Posts Tagged ‘struts2’

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