Saturday, April 12, 2008

Struts tutorial: Struts 1.x in 10 minutes

Preliminary knowledge of JSP/Servlet and web application required. Please visit
http://struts.apache.org/primer.html

Struts is framework implementation of MVC architecture for building web application in J2EE. It built on concept of JSP/Servlet.

In short, struts takes user input from JSP and populate data in actionForms(consist of beans) and provide that inputs to Actions(which perform main operations) by using session and request parameters. After that, we render necessary response using JSP enriched by struts tag library.
For configuration, we use struts-config.xml to bind JSP, forms and action together.

General Terms:

ActionController(struts-config.xml) is controlled by user. it contain mapping and declaration for all form beans, actions, resources, plug-ins, exception handling, error handling etc. This ActionController is fed to ActionServlet which helps in customizing struts based web application.
We use object of ActionMapping for relations defined.

Action Forms=> ActionForms are form beans consist of setters and getter of requested parameters from/to JSP.
Struts try to map html request parameters to action form associated with that display(JSP), struts automatically try to convert request parameter to actionform bean compatible format(like String,Integer,Time,Date etc.).

Action=> Action are performed after value submission from particular JSP/ActionForward, In general, actions are associated with ActionForm which automatically populated and passed as a parameter to Action. Mapping of actions are defined in action controller. Actions are mediator to perform particular operation provided by user input page.



Sessions=> Sessions are automatically maintained by JSP(to avoid @page session=false). In general we use session for passing list/population actionform/messages etc. For this, create instance of that session variable, populate necessary data and save it to session by using
request.getSession().setAttribute("myForm", populatedForm);
here myForm must be defined with same name in struts-config "name attribute" i.e.
under form beans section
<form-bean
name="myForm"
=>Name of Form Bean
type="com.mycompany.myproject.forms.MyForm"/> =>l Type of Form Bean
and actions are

<action
path="/printAction"> -> Action Name provided at JSP
name="myForm" => Name of Form Bean
input="/pages/inputword.jsp" => Input Page in case of error
type="com.mycompany.myproject.actions.PrintAction"/> =>Actual Mapped Action Class
scope="session"> => Defined Scope
<forward
name ="success" => Forward Name to be used in action

path="/pages/printword.jsp" => redirection after success
redirect="true"/>>
<action>






Tag Library:

Tag library are basic components for rendering JSP and providing certain inputs to Actions. It is part of best practices. It is having
property=name corresponding to ActionForm
name= name of form bean which is having that property(By default, JSP is having access to actionforms defined for that page, so for actionform attributes name may not be compulsory)
type: java class which defines type of particular form mean corresponding to given name and property
General Tags:
html:text => generate text box
html:select=>generate combo box
associated with html:optionsCollection or html:options which generate necessary options for that select statement.
html:textarea=>generate text area
html:submit=>submit Form which calls Action at end.
html:reset =>reset form
html:form=> form defination similar to html form tag having action parameter
html:checkbox=> generate checkbox
html:multibox =>generate multiple checkboxes
For using tags, tag library should in included in each JSP.



To generate output

bean:write=> to write particular bean to JSP
logic:iterate=> Used for iteration on basis of particular value defined by name and property, it will generate bean of name given in id attribute.

here id is form bean generated one by one, is part of property myRecordVOs of bean "myForm".
i.e. myList is of type RecordDisplayVO and myRecordVOs is collection of RecordDisplayVO


examples

<%@ taglib uri="/WEB-INF/struts-bean" prefix="bean"%>
<%@ taglib uri="/WEB-INF/struts-html" prefix="html"%>
<%@ taglib uri="/WEB-INF/struts-logic" prefix="logic"%>
<body>

<html:text name="registerForm" property="UserName" tabindex="0" maxlength="50" styleId='userName'
>
<html:textbox name="registerForm" property="Comment" >

<html:select property="typeList" styleId="typeCombo">

<html:optionsCollection property="types" value="typeId" label="typeName"/>
<html:option>Others</html:option>
</html:select>



</body>

here types is Form Bean defined in default actionForm
label is displayed at front end and value picked up and provided to form.



To generate error messages
use input parameter in struts-config to select error page for particular action.Create object of ActionMessages and return mapping.getInputForward(); by action
on jsp end

automatically print error message
Error Messages are generally put in a property file say (MessageResource.properties) having key value pairs like
errors.required={0} is missing.
Here {0} is first input parameter provided in creating errorMessage.
example:

Write in Action:

ActionMessage errorMessage=new ActionMessage("errors.required","name entry");
errorMessages.add(ActionErrors.GLOBAL_MESSAGE, errorMessage);
saveErrors(request,errorMessages);
mapping.getInputForward();

It should generate,
"name entry is missing" in JSP in place of html errors.


To create application using struts, best way to start with IDE.
Create a web project, add struts library to that project. That's all.
For quick learning, refer to existing examples or start with struts-blank application.