Tuesday, December 20, 2016

Flow for Struts2

- Lets say in JSP we allow user to click on url

<!--li><!--s:url var="url" namespace="/test" action="myedit"/><!--s:a href="%{url}">Test<!--/s:a><!--/li>

Action called as myedit will be fired which exist under test namespace

- Search for corrresponding struts.xml and find name space with key word test and inside that namespace find action name as myedit

<!--package name="test" extends="default" namespace="/test">

<!--action name="myedit" class="siddhu.action.TestAction">
<!--result>/WEB-INF/myapplication/editTest.jsp<!--/result>
<!--interceptor-ref name="params" />
<!--interceptor-ref name="basicStack"/>
<!--/action>

- This indicate that result file editTest.jsp will be displayed to the end user.

- Open editTest.jsp and lets assume we had button that save the value user enter into the text field i.e

<!--s:form action="save">
<!--s:textfield label="Name" name="testModel.name"/>
<!--s:submit value="Save" cssClass="btn btn-primary"/>
<!--/s:form>

Above code suggest on form submission save action is called. Refer to the save action in struts.xml

<!--action name="save" class="siddhu.action.TestAction" method="save">
<!--result name="input">/WEB-INF/myapplication/editTest.jsp<!--/result>
<!--result type="redirect">list.action<!--/result>
<!--/action>

above code suggest when user fire save action save method of corresponding TestAction class is called

- Now to map the textfield with action we need to have a model class that store the data of the form that is entered by the end users
- Let say it is TestModel class with getter and setter for the field name
- In TestAction action class make sure to create the instance of private TestModel testName; This is the place where tagging of field on jsp and action take place. In Strut1 it was form class which was helping us for the same. Use prepare() method for the same.

- Perform what ever operation we want to perform in TestAction action save() method 
Note: this testModel in above line must match with the text of <!--s:textfield label="Name" name="testModel.name"/> in jsp and also the name of field in jsp and model need to be same

No comments: