Question

In my Struts2 JSP form, there are text fields and a select tag. For example,

<s:form>
<s:textfield name="name" label="Name"/>
<s:textfield name="dob" label="Date of Birth"/>
<s:select name="degree" list="degreeList" listKey="degreeID" listValue="degreeName"/>
<s:submit/>
</s:form>

Before this JSP is loaded, I filled degreeList in action class. I need to validate this form. So I tried the validation framework. But the problem is action class return "input" itself if the validation failed. I cannot refill the degreeList if the validation failed. So the above JSP cannot be loaded. The error says degreeList is not list/collection as the list is no longer in the value stack. Somebody please kindly guide me how can I validate in another way? Thanks.

Was it helpful?

Solution

All your problem have to be solved is repopulate the lists when you return from the validate() method. I guess your action extends the ActionSupport, if not then you should do it. Override the validate() method. There you should check hasActionErrors() and hasFieldErrors(). If any then repopulate lists. As a good practice you should separate the code that used to render JSP and reuse it in the validate method. After validate() the INPUT result returned without action execution.

OTHER TIPS

Nothing is stopping you from doing validation in execute() and returning what ever result string you wish, or throwing an exception.

But the real issue seems to be "I cannot refill the degreeList if the validation failed", why not, why can't you just send them back to the same form?

You should be able to annotate your action (or use struts.xml) to redirect to the appropriate page should "input" be returned, even if that means a page prior to the form being sent or less reasonably a page stating "sorry you put in the wrong values and because of the time sensitive nature of the form we can never give you the option of trying again :)"

Update:

@Results({ @Result(name="input", location="/package/my-action") })

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top