Home > Java > Replacing Struts s:submit Button With An Image

Replacing Struts s:submit Button With An Image

July 13th, 2009

I wanted to replace the s:submit button of a login form with an image our designer passed to us.

I tried out the most obvious way to do so, but it didn’t produce the expected result. Upon Googling, I came across Eric Martin’s post on an apparent bug in Struts 2.0.11, about the s:submit tag with type=button not rendering properly. I tried out what he posted as that didn’t work either, just as he had stated.

So, I tried something different. I got rid of s:submit button and replaced with a hyperlinked image. The HTML code looked similar to

1
2
3
4
5
6
7
8
9
10
11
12
13
<table align="center">
  <tr>
    <td>
      <s:form action="dologin" method="POST" validate="true">
      <s:textfield name="username" key="label.username"/>
      <s:password name="password" key="label.password"/>
      </s:form>
    </td>
  </tr>
  <tr>
    <td align="right"><a href="javascript: submitForm();"><img src="images/icon_go.png" alt="Sign In" width="27" height="30" align="absbottom" widtd="27"/></a></td>
  </tr>
</table>

The supporting Javascript code is simple and is placed just before closing the head element. The dologin in the document.dologin.submit() (below) is the name assigned to the form by Struts 2. Struts 2 names it dologin based on the name of the action, which is dologin (see line 4 of HTML code snippet above).

<script language="JavaScript">
  function submitForm() { document.dologin.submit(); }
</script>

This worked for me. The image appeared where I wanted it to appear.

Figure 1 : Expected Form Look With s:submit Replaced With An Image

Figure 1 : Expected Form Look With s:submit Replaced With An Image

However, the problem with this approach is that the form validation does not happen within this page itself. What do I mean by that? See Figure 2 (below)

Figure 2

Figure 2

Then upon looking up the documentation for the Submit class at http://struts.apache.org/2.0.14/struts2-core/apidocs/org/apache/struts2/components/Submit.html, i discovered that they already support rendering of a submit button!

So, by replacing the entire code snippet and the supporting Javascript (listed earlier) with the following 4 lines of code, I get the image to appear where I wanted it to appear (see Figure 1 above).

1
2
3
4
5
<s:form action="dologin" method="POST" validate="true">
<s:textfield name="username" key="label.username"/>
<s:password name="password" key="label.password"/>
<s:submit type="image" value="Sign in" src="images/icon_go.png"/>
</s:form>

See the

type="image" along with the src="images/icon_go.png"

My application is using Struts 2.0.11.1.

Categories: Java Tags:
Comments are closed.