Академический Документы
Профессиональный Документы
Культура Документы
Model-View-Controller (MVC) design pattern is used by Struts Framework which is the implementation of the JSP. Struts is open source and is also maintained as a part of Apache Jakarta project. Struts Framework is well suited for application of any size.
2. Define a form bean. This bean has the properties (i.e., getter and setter methods) corresponding to each of the incoming request parameters and normally extends ActionForm and . Alternatively,in which case it will contain a Map representing the request parameters, the bean can extend the DynaActionForm.
3. Create results beans. These are normal beans of which is used in MVC when implemented directly with RequestDispatcher. That is, they represent the data access code and results of the business logic. These beans are stored in request, session, or application scope with the use of setAttribute method of HttpServletRequest, HttpSession, or ServletContext, just as in the normal non-Struts applications.
4. Create an Action object to handle requests. Rather than calling request.getParameter explicitly as in the previous example, we can use the execute method casts the ActionForm argument to the specific form bean class, then uses getter methods to access the properties of the object.
5. Create form that invokes blah.do. This form can use the bean:message tag to output text labels and standard messages that are defined in the properties file that is declared with the message-resources in strutsconfig.xml
6. Display results in JSP. The JSP page uses the bean:write tag to output properties of the result bean and form bean . It may also use the bean:message tag to output text labels and standard messages that are defined in standard properties file.
Centralized File-Based Configuration. Rather than hard-coding information into Java programs, many Struts values are represented in the property or XML files. This loose coupling means that many changes can be made without recompiling or modifying the Java code, and that wholesale changes can be made by editing a single file. This approach also lets Web developers and Java focus on their specific tasks (implementing business logic, presenting certain values to clients, etc.) without needing to know about overall system layout.
Form Beans. In JSP,To automatically populate a JavaBean component based on the incoming request parameters, you can use property="*" with jsp:setProperty . Unfortunately, however, in the standard API this capability is unavailable to the servlets, even though with MVC it is really servlets, not JSP pages, that should usually be the target of form submissions. Apache Struts extends this capability to Java code and adds in several useful utilities, all of which serve to greatly simplify the processing of the request parameters.
Bean Tags. Apache Struts provides a set of custom JSP tags (bean:write, in particular) that let you easily output the properties of JavaBeans component. Basically, these are concise and powerful variations of standard jsp:useBean and jsp:getProperty tags.
HTML Tags. Apache Struts provides a set of custom JSP tags to create HTML forms that are associated with the JavaBeans components. This bean/form association serves two useful purpose:
o o
It lets you get initial form-field values from the Java objects. It lets you to redisplay forms with some or all previously entered values intact.
Form Field Validation. Apache Struts has builtin capabilities for checking that form values are in required format. If values are missing or in an improper format, the form can be automatically redisplayed with the error messages and with the previously entered values maintained. This validation can be performed on server (in Java), or both on server and on client (in JavaScript).
Consistent Approach. Struts encourages consistent use of MVC throughout of your application
Bigger Learning Curve. To use MVC with the standard RequestDispatcher, you need to be comfortable with the standard JSP and servlet API and a large and elaborate framework that is almost equal in size to the core system. This drawback is especially significant with smaller project, nearterm deadlines, and less experienced developers; you could spend as much time learning Struts as building your actual system.
Worse Documentation. Compared to the standard servlets and JSP APIs, Struts has fewer online resources, and many first-time users find the online Apache documentation confusing and poorly organized. There are also fewer books on the Apache Struts than on standard servlets and JSP.
Less Transparent. With Struts applications, there is a lot more going on behind scenes than with normal Java-based Web applications. As a result, Struts applications always are:
o o
Rigid Approach. The flip side of the benefit that Struts encourages a consistent approach to MVC is that Struts makes it difficult to use other approaches.
HTML
y y y y y
If you are going to study these subjects first, find the tutorial on our Home page
//CONTROLLER
The above figure is the MVC architecture 2 model which uses by the Struts.
Installing Tomcat:
Go to the apache site and then download Tomcat and install it. I have downloaded jakartatomcat-5.0.4 and installed for this tutorial only. To test your installation go to your installation directory/bin and to run server,issue startup command .To test the server,open the browser and type http://localhost:8080/ . The browser should display the welcome page. If not before going further,consult the tomcat documentation .
blank.war, struts-example.war and struts-documentation.war from the "jakarta-struts1.1\webapps" directtory into "jakarta-tomcat-5.0.4\webapps" directory. struts-blank.war is useful in creating the struts application from scratch and also the blank struts application .To create our web applications, we will use this file. struts-documentation.war important documents for the struts application development and also contains the API and struts-example.war is the simple MailReader Demonstration Application
The purpose of using Action Class is to translate the HttpServletRequest to the business logic.To use Action we need to overwrite the execute() method and Subclass. All database/business processing are done in the Action Class.Action Class is used perform all the database related stuffs. Using execute() methodthe ActionServlet (commad) passes the parameterized class to Action Form.Struts Framework uses execute method to forward the request to the file as per the value of the returned ActionForward object.The return type of execute method is ActionForward
import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; public class TestAction extends Action { public ActionForward execute( ActionMapping mapping ActionForm form HttpServletRequest request HttpServletResponse response) throws Exception { return mapping.findForward("testAction"); } }
The following code under the <action-mappings> tag is used for mapping TestAction class.
<action path="/TestAction" type="academictutorials.net.TestAction"> <forward name="testAction" path="/pages/TestAction.jsp"/> </action> Click on Test the Action link on the index page if you want to test the new applications. On the user browserthe content of TestAction.jsp should be displayed .
What is ActionForm?
An ActionForm is a JavaBean which extends the org.apache.struts.action.ActionForm. The ActionForm object is automatically populated on the server side with data entered from a form on the client side and ActionForm maintains the session state for the web application and .
ADVERTISEMENT
At first,we will first create the class called AddressForm which extends the ActionForm class.The following code describes ActionForm.java. package academictutorials; import javax.servlet.http.HttpServletRequest; import org.apache.struts.action.*; /** * Form bean for the Address Entry Screen. * */ public class AddressForm extends ActionForm { private String name=null; private String address=null; private String emailAddress=null; public void setName(String name) { this.name=name; } public String getName() { return this.name; } public void setAddress(String address) { this.address=address; } public String getAddress() { return this.address; }
public void setEmailAddress(String emailAddress) { this.emailAddress=emailAddress; } public String getEmailAddress() { return this.emailAddress; } /** * Reset all properties to their default values. * * @param mapping The mapping used to select this instance * @param request The servlet request we are processing */ public void reset(ActionMapping mapping, HttpServletRequest request) { this.name=null; this.address=null; this.emailAddress=null; } /** * Reset all properties to their default values. * * @param mapping The mapping used to select this instance * @param request The servlet request we are processing * @return errors */ public ActionErrors validate( ActionMapping mapping, HttpServletRequest request ) { ActionErrors errors = new ActionErrors(); if( getName() == null || getName().length() < 1 ) { errors.add("name",new ActionMessage("error.name.required")); } if( getAddress() == null || getAddress().length() < 1 ) { errors.add("address",new ActionMessage("error.address.required")); } if( getEmailAddress() == null || getEmailAddress().length() < 1 )
The above class validates Address Form data and populates it. To validate user inputs,the validate() method is used . Error messages are added to ActionMapping object,if any or all of the fields on the form are blank . Note that in the next version ActionError will be removed and now we are using ActionMessage class. Now we will create the model part of the application called Action class. In our action class simply forwards request to the Success.jsp. The following example is the code for AdessAction.java class package academictutorials; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; public class AddressAction extends Action { public ActionForward execute( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { return mapping.findForward("success"); } }
In the struts-config.xml,we have to create an entry for form bean. In struts-config.xml file,add the following lines :
<form-bean name="AddressForm" type="academictytorials.AddressForm"/> In struts-config.xml file,add the following line for handling the action "/Address.do": <action path="/Address" type="roseindia.net.AddressAction" name="AddressForm" scope="request" validate="true" input="/pages/Address.jsp"> <="" td=""> For entering the address details,create the Address.jsp page which is our form . Code for Address.jsp is as follows: <%@ taglib uri="/tags/struts-bean" prefix="bean" %> <%@ taglib uri="/tags/struts-html" prefix="html" %> <html:html locale="true"> <head> <title><bean:message key="welcome.title"/></title> <html:base/> </head> <body bgcolor="white"> <html:form action="/Address"> <html:errors/> <table> <tr> <td align="center"> <font size="4">Please Enter the Following Details</font> </tr> <tr> <td align="right"> Name </td> <td align="left"> <html:text property="name" size="30" maxlength="30"/> </td> </tr> <tr> <td align="right">
Address </td> <td align="left"> <html:text property="address" size="30" maxlength="30"/> </td> </tr> <tr> <td align="right"> E-mail address </td> <td align="left"> <html:text property="emailAddress" size="30" maxlength="30"/> </td> </tr> <tr> <td align="right"> <html:submit>Save</html:submit> </td> <td align="left"> <html:cancel>Cancel</html:cancel> </td> </tr> </table> </html:form> </body> </html:html> At first,the user enters the values in the form and then click on submit form. On the server side,form validation is done.The Eeror message is displays on the jsp page . Use the following code to display the error on the jsp page the <html:errors/> > tag is used. The <html:errors/> tag displays all the errors in one go. To create text box the <html:text .../> nbsp; e.g. <html:text property="address" size="30" maxlength="30"/> To enter the address,the above tag is used.In form-bean,the address is retrieved from and later stored in the property named address. Using <html:submit>Save</html:submit> tag we ca create the submit button and using <html:cancel>Cancel</html:cancel> tag we can create Cancel button. To create a link for testing the Address.jsp form,add the following line in index.jsp. <html:link page="/pages/Address.jsp">Test Address Form</html:link>
To test the newly created screen,build the application and click on the Test the Address Form link on the index page .
At first we have to include following line in our JSP file to use the Struts HTML Tags : <%@ taglib uri="/tags/struts-html" prefix="html" %> above code makes available the tag to jsp.
The following table shows the different HTML tags available in struts
Struts HTML Tags <html:message key="thekey"/> <html:password property="prop" size="10"/> <html:text property="text1" size="5"/> <html:submit>Submit</html:submit> <html:reset>Reset</html:reset> <html:errors/> <html:file property="fileSelectionBox"/> <html:checkbox property="myCheckBox"/> <html:hidden property="hiddenfield"/> Description Looks up the message corresponding to the given key in the message resources and displays it. Tag creates the password field.The string is stored in the property named prop in the form bean. Tag creates the text field.The string is retrieved from and later stored in the property named text1 in the form bean. Tag creates a submit button with the provided content as the button text. Tag creates a reset button with the provided content as the button text. Tag prints all the available error on the page. Tag creates the file upload element on the form.The property must be of the type org.apache.struts.upload.FormFile. Tag creates check box on the form. Tag creates the hidden html element on the form.
<html:radio value="abc" property="myCheckBox"/> <html:select multiple="true" property="selectBox"> <html:textarea property="myTextArea" value="Hello Struts" /> <html:form action="/Address" method="post">
Tag creates the check box on the form. Tag creates list box on the form. The property selectBox must be an array of supported data-types, and the user may select several entries. Use <html:options> to specify the entries. Tag creates the text area on the form.
Tag is used to create the HTML Form for posting the data on the server. Tag generates the base tag. <BASE ...> tells the browser to pretend that the current page is located at some URL other than where the browser found it.Any relative reference will be calculated from the URL given by <BASE HREF="..."> instead of the actual URL. <BASE ...> goes in the <HEAD> section. Tag renders an HTML <html> Element.
<html:base/>
<html:html>
In the Address.jsp which is in previour page we have used some of above tags
It can be use to validate the data on client side as well as on the server side. Struts Framework can be used to validate the form data on the client browser and emits java scripts.By sub classing your From Bean with the DynaValidatorForm class,server side validation of the form can be accomplished . David Winterfeldt developed the Validator framework as third-party add-on to the Struts.Now the Validator framework can be used with or without the Struts and it is a part of Jakarta Commons project .The Validator framework can be used without doing any extra settings and comes integrated with Struts Framework.
validation requirements are applied to the form and aslo can be defined.In validator framework,we can plug in our own custom validations into Validator. The Validator Framework uses two XML configuration files called validator-rules.xml and validation.xml. Standard validation routines are defined by the validator-rules.xml and used in validation.xml. To define form specific validations,validation.xml is used.To define the validations applied to a form bean,the validation.xml
Structure of validator-rule.xml
The validation-rules.xmldeclares and assigns the logical names to the validation routines and is provided with Validator Framework. For each validation routine,it also contains client-side javascript code . To perform specific validations,the validation routines are the java methods plugged into the system . Following table contains the details of the elements in this file: Element Attributes and Description
formThis is the root node. It contains nested elements for all of the other configuration validation settings. global The validator details specified within this, are global and are accessed by all forms. The validator element defines what validators objects can be used with the fields referenced by the formset elements. The attributes are:
y y y y y
validator
y y
name: Contains a logical name for the validation routine classname: Name of the Form Bean class that extends the subclass of ActionForm class method: Name of the method of the Form Bean class methodParams: parameters passed to the method msg:Validator uses Struts' Resource Bundle mechanism for externalizing error messages. Instead of having hard-coded error messages in the framework, Validator allows you to specify a key to a message in the ApplicationResources.properties file that should be returned if a validation fails. Each validation routine in the validator-rules.xml file specifies an error message key as value for this attribute. depends: If validation is required, the value here is specified as 'required' for this attribute. jsFunctionName: Name of the javascript function is specified here.
Contains the code of the javascript function used for client-side validation. Starting in Struts 1.2.0 the default javascript definitions have been consolidated to javascript commons-validator. The default can be overridden by supplying a <javascript> element with a CDATA section, just as in struts 1.1. The Validator plug-in which is also known as validator-rules.xml is supplied with the predefined set of commonly used validation rules such as Required, Minimum Length, Maximum length, Date Validation, Email Address validation and more. If required,this basic set of rules can also be extended with the custom validators .
Structure of validation.xml
This validation.xml configuration file define which validation routines that is used to validate Form Beans and also you can define validation logic for any number of Form Beans in this configuration file . Inside that definition, you specify validations you want to apply to the Form Bean's fields and the definition in this file use the logical names of Form Beans from the strutsconfig.xml file along with the logical names of validation routines from the validator-rules.xml file to tie the two together. The following table shows the elements of the validation.xml file Element formvalidation global constant constantname constantvalue formset Attributes and Description This is the root node. It contains nested elements for all of the other configuration settings The constant details are specified in <constant> element within this element. Constant properties are specified within this element for pattern matching. Name of the constant property is specified here Value of the constant property is specified here. This element contains multiple <form> elements This element contains the form details. The attributes are: name: Contains the form name. Validator uses this logical name to map the validations to a Form Bean defined in the struts-config.xml file field This element is inside the form element, and it defines the validations to apply to specified Form Bean fields.
form
property: Contains the name of a field in the specified Form Bean depends: Specifies the logical names of validation routines from the validator-rules.xml file that should be applied to the field.
A key for the error message to be thrown incase the validation fails, is specified here Contains the variable names and their values as nested elements within this element. The name of the criteria against which a field is validated is specified here as a variable The value of the field is specified here
To validates the user input on the browser,validator Framework emits the JavaScript code. Follow these steps to accomplish this: 1. Enabling the Validator plug-in: This makes Validator available to the system itself. 2. Create Message Resources To display error message to the user. 3. Developing the Validation rulesIn validation.xml,we have to define the validation rules for the address form. Struts Validator Framework uses this rule for generating JavaScript for validation. 4. Applying the rules: For generation of JavaScript,we are required to add the appropriate tag to JSP. 5. Build and test: Before the testing,we are required to build the application once the above steps are done .
We are adding only one validation that fields on the form should not be blank in this application. Add the following code in validation.xml to validate the form. <!-- Address form Validation--> <form name="AddressForm"> <field property="name" depends="required"> <arg key="AddressForm.name"/> </field> <field property="address" depends="required"> <arg key="AddressForm.address"/> </field> <field property="emailAddress" depends="required"> <arg key="AddressForm.emailAddress"/> </field> </form> The above example defines validation for the form fields name, address and emailAddress. To check that the fields are not left blank,the attribute depends="required" is used to instructs Validator Framework to generate the JavaScript .JavaScript shows error message,if the fields are left blank .The message are taken from the key defined in <arg key=".."/> tag in the error message.We can take the value from message resources (Struts\strutstutorial\web\WEBINF\MessageResources.properties).
<p> This application shows the use of Struts Validator.<br> The following form contains fields that are processed by Struts Validator.<br> Fill in the form and see how JavaScript generated by Validator Framework validates the form. </p> <p> <html:errors/> </p> <table> <tr> <td align="center" colspan="2"> <font size="4"><b>Please Enter the Following Details</b></font> </tr> <tr> <td align="right"> <b>Name</b> </td> <td align="left"> <html:text property="name" size="30" maxlength="30"/> </td> </tr> <tr> <td align="right"> <b>Address</b> </td> <td align="left"> <html:text property="address" size="30" maxlength="30"/> </td> </tr> <tr> <td align="right"> <b>E-mail address</b> </td> <td align="left"> <html:text property="emailAddress" size="30" maxlength="30"/> </td> </tr> <tr> <td align="right"> <html:submit>Save</html:submit>
</td> <td align="left"> <html:cancel>Cancel</html:cancel> </td> </tr> </table> </div> <!-- Begin Validator Javascript Function--> <html:javascript formName="AddressForm"/> <!-- End of Validator Javascript Function--> </html:form> </body> </html:html> To plug-in Validator JavaScript,the code <html:javascript formName="AddressForm"/> is used . In struts-config.xml,create the following entry for the mapping the /AddressJavascriptValidation url for handling the form submission through AddressJavascriptValidation.jsp. <action path="/AddressJavascriptValidation" type="roseindia.net.AddressAction" name="AddressForm" scope="request" validate="true" input="/pages/AddressJavascriptValidation.jsp"> <forward name="success" path="/pages/success.jsp"/> </action> To call the form,add the following line in index.jsp. <li> <html:link page="/pages/AddressJavascriptValidation.jsp">Client Side Validation for Address Form</html:link> <br> The Address Form that validates the data on the client side using Stuts Validator generated JavaScript. </li>
Browser shows the error message,if the fields are left blank and Save button is clicked,
To development user interface,Tiles framework is used. By assembling the reusable tiles (jsp, html, etc..),tiles is enables the developers to develop web applications.
ADVERTISEMENT
Tiles nables the developers to define a template for web site and uses the concept of reuse and then use this layout to populate the content of the web site.
<table border="1" cellpadding="0" cellspacing="0" width="100%" bordercolor="#000000" bgcolor="#E7FDFE"> <tr> <td width="100%" colspan="2" valign="top"><tiles:insert attribute="header"/></td> </tr> <tr> <td width="23%"><tiles:insert attribute="menu"/></td> <td width="77%" valign="top" valign="top"><tiles:insert attribute="body"/></td> </tr> <tr> <td width="100%" colspan="2" valign="top"><tiles:insert attribute="bottom"/></td> </tr> </table> </body> </html> You can use the appropriate html to define structure for web application and did the following things: Referenced /WEB-INF/struts-tiles.tld TLD file. To display the title using the tiles:getAsString tag,use the string parameters. Ignore missing parameter ,if the attribute ignore="true" then Tiles. If this is true in case the parameter is missing then the Tiles framework will through exception . The tiles:insert tag is used to insert the contents JSP, which inserts any page or web resources that framework refers to as a title. For Example <tiles:insert attribute="header"/> inserts header web page.
<tiles:insert page="/tiles/template.jsp" flush="true"> <tiles:put name="title" type="string" value="Welcome" /> <tiles:put name="header" value="/tiles/top.jsp" /> <tiles:put name="menu" value="/tiles/left.jsp" /> <tiles:put name="body" value="/tiles/content.jsp" /> <tiles:put name="bottom" value="/tiles/bottom.jsp" /> </tiles:insert> The code <tiles:insert page="/tiles/template.jsp" flush="true"> specify the tiles layout page to be used. We have set the flush attribute to true, this makes tile file to be written to browser before the rest of the page. To specify the title of page <tiles:put name="title" type="string" value="Welcome" /> is used. The following code is used to insert actual pages in the template.: <tiles:put name="header" value="/tiles/top.jsp" /> <tiles:put name="menu" value="/tiles/left.jsp" /> <tiles:put name="body" value="/tiles/content.jsp" /> <tiles:put name="bottom" value="/tiles/bottom.jsp" /> The content.jsp wil be inserted in the layout's body region and the bottom.jsp will be inserted in bottom region.The top.jsp will be inserted in the layout's header of the region. The left.jsp will be inserted in layout's menu region. .
T o generate the output in Tiles we can define the definition in tiles-defs.xml which specifies the different components to "plugin" .
ADVERTISEMENT
We can eliminates the need to define extra jsp file for the each content file by using tilesdefs.xml.
For example,we have defined example.jsp to display the content of the content.jsp file in the last section.
In this section I will show you using the tiles-defs.xml file how to eliminate the need of extra jsp file.
Steps to Use the tiles-defs.xml Setup the Tiles plugin in the struts-config.xml file.
In struts-config.xml,add the following code. We use the /WEB-INF/tiles-defs.xml file to enable TilesPlugin <plug-in className="org.apache.struts.tiles.TilesPlugin" > <!-- Path to XML definition file --> <set-property property="definitions-config" value="/WEB-INF/tiles-defs.xml" /> <!-- Set Module-awareness to true --> <set-property property="moduleAware" value="true" /> </plug-in>
should looks like: <?xml version="1.0" encoding="ISO-8859-1" ?> <!DOCTYPE tiles-definitions PUBLIC "-//Apache Software Foundation//DTD Tiles Configuration 1.1//EN" "http://jakarta.apache.org/struts/dtds/tiles-config_1_1.dtd"> <tiles-definitions>
<definition name="Tiles.Example" page="/tiles/template.jsp"> <put name="title" type="string" value="Welcome" /> <put name="header" value="/tiles/top.jsp" /> <put name="menu" value="/tiles/left.jsp" /> <put name="body" value="/tiles/content.jsp" /> <put name="bottom" value="/tiles/bottom.jsp" /> </definition> <definition name="${YOUR_DEFINITION_HERE}"> </definition> </tiles-definitions>
DynamicActionForm eliminates the need of the FormBean class.The form bean definition can be written into the struts-config.xml file.
To reduce the development time for the developer,it makes FormBean declarative .
ADVERTISEMENT
To create a Java class for each type of form bean,DynamicActionForm is used as the specialized subclass of ActionForm that allows the creation of the form beans with dynamic sets of properties, without requiring the developer.
We will recreate add form with the help of DynaActionForm in this tutorial. In the action class,it also shows you how you can validate the use input.
name="DynaAddressForm" scope="request" validate="true" input="/pages/DynaAddress.jsp"> <forward name="success" path="/pages/success.jsp"/> <forward name="invalid" path="/pages/DynaAddress.jsp" /> </action>
} if(((String)addressForm.get("address")).equals("")) { errors.add("address",new ActionMessage("error.address.required")); } if(((String)addressForm.get("email")).equals("")) { errors.add("email",new ActionMessage("error.emailaddress.required")); } //Saves the error saveErrors(request,errors); //Forward the page if(errors.isEmpty()) { return mapping.findForward("success"); } else { return mapping.findForward("invalid"); } } }
<tr> <td align="right"> Name </td> <td align="left"> <html:text property="name" size="30" maxlength="30"/> </td> </tr> <tr> <td align="right"> Address </td> <td align="left"> <html:text property="address" size="30" maxlength="30"/> </td> </tr> <tr> <td align="right"> E-mail address </td> <td align="left"> <html:text property="email" size="30" maxlength="30"/> </td> </tr> <tr> <td align="right"> <html:submit>Save</html:submit> </td> <td align="left"> <html:cancel>Cancel</html:cancel> </td> </tr> </table>
</html:form> </body> </html:html> In index.jsp,add the following line to call the form. <li> <html:link page="/pages/DynaAddress.jsp">Dyna Action Form Example</html:link> <br> Example shows you how to use DynaActionForm. </li>
It is the only class or interface in the upload package which is typically referenced directly by a Struts application
*/ public class StrutsUploadForm extends ActionForm { private FormFile theFile; /** * @return Returns the theFile. */ public FormFile getTheFile() { return theFile; } /** * @param theFile The FormFile to set. */ public void setTheFile(FormFile theFile) { this.theFile = theFile; } }
{ public ActionForward execute( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { StrutsUploadForm myForm = (StrutsUploadForm)form; // Process the FormFile FormFile myFile = myForm.getTheFile(); String contentType = myFile.getContentType(); String fileName = myFile.getFileName(); int fileSize = myFile.getFileSize(); byte[] fileData = myFile.getFileData(); System.out.println("contentType: " + contentType); System.out.println("File Name: " + fileName); System.out.println("File Size: " + fileSize); return mapping.findForward("success"); } }
<tr> <td align="right"> File Name </td> <td align="left"> <html:file property="theFile"/> </td> </tr>
</html:form> </body> </html:html> Note that we have set the encrypt property of form to enctype="multipart/form-data". The following code for the success page (uploadsuccess.jsp) is as follows: <html> <head> <title>Success</title> </head> <body> <p align="center"><font size="5" color="#000080">File Successfully Received</font></p> </body> </html>
In index.jsp to call the form,add the following line. <li> <html:link page="/pages/FileUpload.jsp">Struts File Upload</html:link> <br> Example shows you how to Upload File with Struts. </li>
In this tutorial to use MySQL Database ,we will configure the Struts DataSource Manager and use the connection provided by Struts DataSource in action class.
Download Struts
You can download the Struts struts-1.2.7 from http://struts.apache.org/download.cgi and unzip it to your favorite directory. Go to struts-1.2.7\webapps directory and then unzip struts-blank.war file and We will use this file to write our tutorial also.
"org.apache.tomcat.dbcp.dbcp.BasicDataSource". In tomcat 5.5.9 dbcp classes are packaged in the naming-factory-dbcp.jar archieve, so instead of "org.apache.commons.dbcp.BasicDataSource" we are using "org.apache.tomcat.dbcp.dbcp.BasicDataSource". After this in the <data-sources> tag,change database dirver, database url and passwor. You <data-source> attributes are as follows: <data-sources> <data-source type="org.apache.tomcat.dbcp.dbcp.BasicDataSource"> <set-property property="driverClassName" value="com.mysql.jdbc.Driver" /> <set-property property="url" value="jdbc:mysql://localhost:3306/strutsdatabase?autoReconnect=true" /> <set-property property="username" value="root" /> <set-property property="password" value="" /> <set-property property="maxActive" value="10" /> <set-property property="maxWait" value="5000" /> <set-property property="defaultAutoCommit" value="false" /> <set-property property="defaultReadOnly" value="false" /> <set-property property="validationQuery" value="SELECT COUNT(*) FROM test" /> </data-source> </data-sources>
package test; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import java.sql.*; public class TestDataSource extends Action { public ActionForward execute( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { javax.sql.DataSource dataSource; java.sql.Connection myConnection=null; try { dataSource = getDataSource(request); myConnection = dataSource.getConnection(); Statement stmt=myConnection.createStatement(); ResultSet rst=stmt.executeQuery("select username from test"); System.out.println("******************************************"); System.out.println("********Out Put from TestDataSource ******"); while(rst.next()) { System.out.println("User Name is: " + rst.getString("username")); } System.out.println("******************************************"); rst.close(); stmt.close(); // do what you wish with myConnection } catch (SQLException sqle) { getServlet().log("Connection.process", sqle); } finally
{ //enclose this in a finally block to make //sure the connection is closed try { myConnection.close(); } catch (SQLException e) { getServlet().log("Connection.close", e); } } return mapping.findForward("success"); } } To get the data source,following code is used and then connection from the Struts DataSource: dataSource = getDataSource(request); myConnection = dataSource.getConnection();
Go to the jakarta-tomcat-5.5.9\webapps\strutsdatabase\WEB-INF\src\java\test directory and then save this file(TestDataSource.java). Then add the servlet API into class path. Then open dos prompt and navigate to the jakarta-tomcat-5.5.9\webapps\strutsdatabase\WEB-INF\src\ directory and issue run ant and this will compile action class (TestDataSource.java) and copy it to the classes directory of the webapplication.