Saturday, March 31, 2012

struts JSP set value for s:textfield, s:submit

In JSP when using struts to create forms, the fields like s:textfield, s:submit .etc have an attribute named 'value'.

This value cannot be dynamically set using direct jsp tags. If you try something like this

<s:hidden name="form" value="<%=System.currentTimeMillis() %>" />


 you'll get

"According to TLD or attribute directive in tag file, attribute value does not accept any expressions".


Check this struts reference for 'value is and Object' part.
http://struts.apache.org/2.0.6/docs/tag-syntax.html.

This is how struts defines it's fields in s:textfield, s:submit .etc attributes. Trying to insert <% %> tags into this will be very difficult. However, we can remove s:textfield and replace it with the corresponding html tags.

Example:
<s:hidden name="form" value="studentsList" />
 will be
<input type="hidden" name="form" value="studentsList" id="Forms_form"/>


when passed through struts.


In the same way
<s:submit value="Students List"/>


will be
<tr> <td colspan="2"> <div align="right"> <input type="submit" id="Forms_0" value="Students List"/> </div> </td> </tr>


Now we can use <%= %> tags inside the value fields as below.


<td colspan="2">
<div align="right">
<input type="submit" id="Forms_0" value="<%= s.getFirstName()+" "+s.getLastName() %>"/>
</div>
</td>


The best way to do this is first complete the forms fields setting the required field value to any string. Use the s:textfield tags and set value="xxx". Then deploy the project and view the page source. The run the project and in the relevant page view the page source(Ctrl+U). This will show you the converted html form of the struts form. Copy the relevant field and insert the JSP scripts to value. value="<%=System.currentTimeMillis()%>". Now it should work!!!

Struts JSP style="display:none" not working?

When I wanted to hide some 'div's from my JSP page, when I used

<div id="tab1" class="tabContent" style="display: none;">
This proves to be working on simple html version

<form name="ff".... >

But when I added struts form

<s: form action="StudentDetailsForm">
this makes the 'display:block' function freeze. This also happens to only some of the long forms.

To fix this what I did was set the struts form theme to simple and it worked!!!


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