Wednesday, July 23, 2003

Here's my first attempt a blog.

I've been learning a lot about Struts lately and thought it would be good to write things down to pass on to my colleagues. It occurred to me that a blog might be the answer, so I'm going to give it a try. I'll jump right in to the things I learned today.

Initializing a form. Because Struts wants you to have an Action to handle every request, I was thinking I had to initialize my ActionForm in an Action in order to prepopulate data in JSP form. This isn't true and in fact it won't work if you have validation turned on (you are validating your forms, right?) . The trouble is, your Action is never reached if the form fails its validation check. Instead, the browser is sent to whatever page you have defined as the "input" for the Action (usually the .jsp with the <html:form>). The answer is to initialize the form by overriding ActionForm.reset(). Do whatever you need to prepopulate the form here. Then, define the actions like this:

<!-- Action to initialize the form -->
<action path="/initializeForm" forward="/myform.jsp" />

<!-- Action to save the data entered in the form -->
<action path="/saveForm"
input="/myform.jsp"
type="com.foo.MyForm"
validate="true" >
<forward name="success" path="/yay.html" />
</action>


The reset() gets called when the Form is instantiated. That happens in your JSP when the <html:form> tag is encountered. Incidentally, if your forms have request scope, doesn't that mean they'll be initialized twice? So the prepopulation data, which may not be needed on the server side, will have to be generated twice? Hmm. There must be a way to avoid that.

I tried to get the struts-el tags working today, and met with very limited success. It appears there is a bug in the Jasper JSP compiler JspC that causes it to choke on the struts-el tags if JspC is run outside of Tomcat. This happens when you either a) precompile your JSPs using Ant or b) try to compile your JSP in Netbeans. I do both of these frequently, so that pretty much rules out the use of these tags until this bug is fixed.

No comments: