Struts Web Framework With Netbeans
Do Your First Step to Struts Web Framework With Netbeans 
This document takes you through the basics of using NetBeans IDE to develop web applications using the Struts web framework. Strut is an open-source framework that extends the Java
            Servlet API and employs a Model,
            View, Controller (MVC) architecture. It enables you to create maintainable, extensible,
            and flexible web applications based on standard technologies, such as JSP pages, JavaBeans,
            resource bundles, and XML.
This tutorial teaches you how to build a simple MVC application that displays a login page and returns a success page upon submitting data that passes validation. You learn several basic features provided by Struts, as well as how these features are implemented using the IDE. Specifically, you use Struts tags in JSP pages, maintain user data with a Struts
For a more fine-grained introduction to Struts, see How do Struts work? on the official Struts website. Also, make use of the IDE's Javadoc Index Search (Help > Javadoc Index Search) to view the Struts Framework API, which is packaged with the Struts libraries.[ left-sidebar ]
Contents
 
        
            
Notes:
 Developing a Struts application is similar to developing any other kind of web application in NetBeans IDE. However, you complement your web development toolkit by taking advantage of the Struts support provided by the IDE. For example, you use templates in the IDE to create
            Struts
        
Developing a Struts application is similar to developing any other kind of web application in NetBeans IDE. However, you complement your web development toolkit by taking advantage of the Struts support provided by the IDE. For example, you use templates in the IDE to create
            Struts 
The following steps demonstrate how to create a simple form that collects user data, performs simple validation, and outputs the data on a success page.
        
 Note: Use the Files window (Window > Files) to see all of
            your project contents in a directory-based view.
        
Note: Use the Files window (Window > Files) to see all of
            your project contents in a directory-based view.
The Struts-specific configuration files, as well as the application's deployment descriptor, are conveniently placed within the Configuration Files folder. Open the deployment descriptor (double-click the
        
            
        
Creating an 
A Struts 
Creating an 
The 
            
            
        
Adding 
In order for the application to match JSP pages with forwarding conditions returned by 
        
This tutorial teaches you how to build a simple MVC application that displays a login page and returns a success page upon submitting data that passes validation. You learn several basic features provided by Struts, as well as how these features are implemented using the IDE. Specifically, you use Struts tags in JSP pages, maintain user data with a Struts
ActionForm
            bean, and implement forwarding logic using a Struts Action object. You are also
            shown how to implement simple validation to your application, including setting up a warning message for a failed login attempt.For a more fine-grained introduction to Struts, see How do Struts work? on the official Struts website. Also, make use of the IDE's Javadoc Index Search (Help > Javadoc Index Search) to view the Struts Framework API, which is packaged with the Struts libraries.[ left-sidebar ]
Contents
- Overview of the Application
- Setting Up a Struts Application
- Creating JSP Pages
- Creating an ActionFormBean
- Creating an ActionClass
- Implementing Validation
- Adding forwardEntries tostruts-config.xml
- Configuring and Running the Application
- See Also
| Software or Resource | Version Required | 
|---|---|
| NetBeans IDE | 6.8, 6.9, 7.0, 7.1, Java EE bundle | 
| Java Development Kit (JDK) | 6 | 
| GlassFish server or Tomcat servlet container | Open Source Edition 3.x version 6.x or 7.x | 
- The Java installation enables you to optionally install the GlassFish server and the Apache Tomcat servlet container. You must install one of these (or register a different server in the IDE) to work through this tutorial.
- If you need to compare your project with a working solution, you can download the sample application.
Overview of the Application
When you use Struts, the framework provides you with a controller servlet,ActionServlet,
            which is defined in the Struts libraries that are included in the IDE, and which is automatically
            registered in the web.xml deployment descriptor as shown
            below. The controller servlet uses a struts-config.xml file to map incoming
            requests to Struts Action objects, and instantiate any ActionForm objects
            associated with the action to temporarily store form data. The Action object processes
            requests using its execute the method, while making use of any data stored in the form
            bean. Once the Action object processes a request, it stores any new data (i.e., in
            the form bean, or in a separate result bean), and forwards the results to the appropriate
            view.Action objects and ActionForm beans. Upon creation, the IDE
            automatically registers these classes in the struts-config.xml file and lets
            you extend this file very easily using menu items in the Source Editor's right-click menu.
            Because many web applications use JSP pages for the view, Struts also provides custom tag libraries that facilitate interaction with HTML forms. Within the IDE's Source Editor, you can invoke code completion and Javadoc support that helps you to work efficiently with these libraries.The following steps demonstrate how to create a simple form that collects user data, performs simple validation, and outputs the data on a success page.
Setting Up a Struts Application
In the IDE, a Struts application is nothing more than a normal web application accompanied by the Struts libraries and configuration files. You create a Struts application in the same way as you create any other web application in the IDE - using the New Web Application wizard, with the additional step of indicating that you want the Struts libraries and configuration files to be included in your application.- Choose File > New Project (Ctrl-Shift-N; ⌘-Shift-N on Mac) from the main menu. Under Categories, select Web. Under Projects, select Web Application and click Next.
- In the Name and Location panel, enter MyStrutsAppfor Project Name and click Next.
- In the Server and Settings panel, select the server to which you want to deploy your application. Only servers that are registered with the IDE are listed. (To register a
                server, click Add next to the Server drop-down list.) Also, note that the Context Path
                to your deployed application becomes /MyStrutsApp. Click Next.
- In the Frameworks panel, select Struts:
                
 
 For purposes of this tutorial, do not change any of the configuration values in the lower region of this panel. These are the following:- Action Servlet Name: The name of the Struts action servlet used
                        in the application. The web.xmldeployment descriptor contains an entry for the action servlet and specifies the appropriate Struts-specific parameters, such as the path to the servlet class within the Struts library and to thestruts-config.xmlconfiguration file within the application.
- Action URL Pattern: Specifies the patterns of incoming requests which are mapped to the Struts action controller. This generates a mapping entry in the deployment descriptor. By default, only the *.dothe pattern is mapped.
- Application Resource: Lets you specify the resource bundle which will be used in the struts-config.xmlfile for localizing messages. By default, this iscom.myapp.struts.ApplicationResource.
- Add Struts TLDs: Lets you generate tag library descriptors for the Struts tag libraries. A tag library descriptor is an XML document that contains additional information about the entire tag library as well as each individual tag. In general, this is not necessary, because you can refer to on-line URIs rather than local TLD files.
 
- Action Servlet Name: The name of the Struts action servlet used
                        in the application. The 
- Click Finish. The IDE creates the project folder in your file system. As with any web application in the IDE, the project folder contains all of your sources and the IDE's project metadata, such as the Ant build script. However, your web application in addition has all of the Struts libraries on its classpath. Not only are they on the application's classpath, but they are included in the project and will be packaged with it later when you build the project.
The Struts-specific configuration files, as well as the application's deployment descriptor, are conveniently placed within the Configuration Files folder. Open the deployment descriptor (double-click the
web.xml file node to have it display in the Source Editor). In order to handle Struts processing, a mapping is provided for the
            Struts controller servlet:<servlet>
    <servlet-name>action</servlet-name>
    <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
    <init-param>
        <param-name>config</param-name>
        <param-value>/WEB-INF/struts-config.xml</param-value>
    </init-param>
    <init-param>
        <param-name>debug</param-name>
        <param-value>2</param-value>
    </init-param>
    <init-param>
       <param-name>detail</param-name>
       <param-value>2</param-value>
    </init-param>
    <load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>action</servlet-name>
    <url-pattern>*.do</url-pattern>
</servlet-mapping>
Above, the Struts controller servlet is named action and is defined in the Struts
            library (org.apache.struts.action.ActionServlet). It is set to handle all requests
            that satisfy the *.do mapping. In addition, initialization parameters for the servlet
            are specified by means of the struts-config.xml file, also contained in the WEB-INF
            folder.Creating JSP Pages
Begin by creating two JSP pages for the application. The first displays a form. The second is the view returned when login is successful?Creating a Login Page
- Right-click the MyStrutsAppproject node, choose New > JSP, and name the new filelogin. Click Finish. Thelogin.jspthe file opens in the Source Editor.
- In the Source Editor, change the content of both the <title>and<h1>tags (or<h2>tags, depending on the IDE the version you are using) toLogin Form.
- Add the following two taglib directives to the top of the file:
<%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %> <%@ taglib uri="http://struts.apache.org/tags-html" prefix="html" %> Many web applications use JSP pages for views in the MVC paradigm, so Struts provides custom tag libraries that facilitate interaction with HTML forms. These can be easily applied to a JSP file using the IDE's support for code completion. When you type in the Source Editor, the IDE provides you with code completion for Struts tags, as well as the Struts Javadoc. You can also invoke code completion manually by pressing Ctrl-Space:
 
 The bean taglib provides you with numerous tags that are helpful when associating a form bean (i.e., anActionFormbean) with the data collected from the form. The HTML taglib offers an interface between the view and other components necessary to a web application. For example, below you replace common htmlformtags with Struts'<html:form>tags. One benefit this provides is that it causes the server to locate or create a bean object that corresponds to the value provided forhtml:form'sactionelement.
- Below the <h1>(or<h2>) tags, add the following:<html:form action="/login"> <html:submit value="Login" /> </html:form> Whenever you finish typing in the Source Editor, you can tidy up the code by right-clicking and choosing Format (Alt-Shift-F).
- In the Palette (Window > Palette) in the right region of the IDE, drag a Table item from the HTML category to a point just above the <html:submit value="Login" />line. The Insert Table dialog box displays. Set the rows to3, columns to2, and leave all other settings at0. Later in the tutorial, you will attach a stylesheet to affect the table display.
 
 Click OK, then optionally reformat the code (Alt-Shift-F). The form inlogin.jspnow looks as follows:<html:form action="/login"> <table border="0"> <thead> <tr> <th></th> <th></th> </tr> </thead> <tbody> <tr> <td></td> <td></td> </tr> <tr> <td></td> <td></td> </tr> <tr> <td></td> <td></td> </tr> </tbody> </table> <html:submit value="Login" /> </html:form>Note: You can safely delete the<thead>table row, as it is not used in this tutorial.
- In the first table row, enter the following (changes in bold):
<tr> <td>Enter your name:</td> <td><html:text property="name" /></td> </tr>
- In the second table row, enter the following (changes in bold):
<tr> <td>Enter your email:</td> <td><html:text property="email" /></td> </tr>Thehtml:textelement enables you to match the input fields from the form with properties in the form bean that will be created in the next step. So for example, the value ofpropertymust match a field declared in the form bean associated with this form.
- Move the <html:submit value="Login" /> element into
                    the second column of the third table row, so that the third table row
                    appears as follows (changes in bold):
<tr> <td></td> <td><html:submit value="Login" /></td> </tr>
<html:form action="/login">
    <table border="0">
        <tbody>
            <tr>
                <td>Enter your name:</td>
                <td><html:text property="name" /></td>
            </tr>
            <tr>
                <td>Enter your email:</td>
                <td><html:text property="email" /></td>
            </tr>
            <tr>
                <td></td>
                <td><html:submit value="Login" /></td>
            </tr>
        </tbody>
    </table>
</html:form>
            Creating a Success Page
- Right-click the MyStrutsAppproject node, choose New > JSP, and name the new filesuccess. In the Folder field, click the adjacent Browse button and selectWEB-INFfrom the dialog that displays. Click Select Folder to enter WEB-INF in the Folder field. Any files contained in the WEB-INF folder are not directly accessible to client requests. In ordersuccess.jspto be properly displayed, it must contain processed data. Click Finish.
- In the Source Editor, change the content of the newly created page to the following:
<head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Login Success</title> </head> <body> <h1>Congratulations!</h1> <p>You have successfully logged in.</p> <p>Your name is: .</p> <p>Your email address is: .</p> </body>
- Add a bean taglib
                    directive to the top of the file:
<%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %> 
- Add the following <bean:write>tags (changes in bold):<p>Your name is: <bean:write name="LoginForm" property="name" />.</p> <p>Your email address is: <bean:write name="LoginForm" property="email" />.</p> By employing the<bean:write>tags, you make use of the bean taglib to locate theActionFormbean you are about to create, and display the user data saved fornameandemail.
Creating an ActionForm Bean
A Struts ActionForm bean is used to persist data between requests. For example, if
            a user submits a form, the data is temporarily stored in the form bean so that it can either
            be redisplayed in the form page (if the data is in an invalid format or if login fails) or
            displayed in a login success page (if data passes validation).- Right-click the MyStrutsAppproject node and choose New > Other. Under Categories choose Struts, then under File Types choose Struts ActionForm Bean. Click Next.
- Type in LoginFormfor the Class Name. Then selectcom.myapp.strutsin the Package drop-down list and click Finish. The IDE creates theActionFormbean and opens it in the Source Editor. By default, the IDE provides it with aStringcallednameand anintcallednumber. Both fields have accessor methods defined for them. Also, the IDE adds a bean declaration to thestruts-config.xmlfile. If you open thestruts-config.xmlfile in the Source Editor, you can see the following declaration, which was added by the wizard:
 <form-beans> <form-bean name="LoginForm" type="com.myapp.struts.LoginForm" /> </form-beans>The IDE provides navigation support in thestruts-config.xmlfile. Hold down the Ctrl key and hover your mouse over theActionFormbean's fully qualified class name. The name becomes a link, enabling you to navigate directly to the class in the Source Editor:
 
- In the ActionFormbean in the Source Editor, create fields and accompanying accessor methods that correspond to thenameandemailtext input fields that you created inlogin.jsp. Becausenamehas already been created in theActionFormskeleton, you only need to implementemail. Add the following declaration beneathname(changes in bold):
 private String name; private String email; To create accessor methods, place your cursor onemailand press Alt-Insert.
 Select Getter and Setter, then in the dialog that displays, select email : String, and click Generate. Accessor methods are generated for theemailfield.
 Note: You can delete the declaration and accessor methods fornumber, as it is not used in this tutorial.
Creating an Action Class
The Action the class contains the business logic in the application. When form data is received, it is the execute method of an Action an object that processes the data and determines which view to forward the processed data. Because the Action
            class is integral to the Struts framework, NetBeans IDE provides you with a wizard.- In the Projects window, right-click the MyStrutsAppproject node and choose New > Other. From the Struts, category choose Struts Action and click Next.
- In the Name and Location panel, change the name to LoginAction.
- Select com.myapp.strutsin the Package drop-down list.
- Type /loginin Action Path. This value must match the value you set for theactionattribute of the<html:form>tags inlogin.jsp. Make sure settings appear as in the screenshot below, then click Next.
 
- In the third step of the wizard, you are given the opportunity to associate the Actionclass with a form bean. Notice that theLoginFormbean you previously created is listed as an option for ActionForm Bean Name. Make the following adjustments to the panel:- Delete the forward slash for the Input Resource field
- Set Scope to Request (Session is the default scope setting in Struts.)
- Deselect the Validate ActionForm Bean option
 LoginActionclass is generated, and the file opens in the Source Editor. Also, note that the followingactionentry is added to thestruts-config.xmlfile:<action-mappings> <action name="LoginForm" path="/login" scope="request"type="com.myapp.struts.LoginAction" validate="false"/> <action path="/Welcome" forward="/welcomeStruts.jsp"/> </action-mappings>Thenameandscopeattributes apply to the form bean that is associated with the action. Specifically, when an incoming request matches/login, the Struts framework automatically instantiates aLoginFormobject and populates it with the form data sent in the request. The default value ofvalidateis set totrue. This tells the framework to call thevalidatemethod of the form bean. You deselected this option in the wizard however because you will hand-code simple validation in the next step, which does not require thevalidatemethod.
Implementing Validation
In the Source Editor, browse through theLoginAction class and look at the execute
            method:public ActionForward execute(ActionMapping mapping, ActionForm form,
    HttpServletRequest request, HttpServletResponse response)
    throws Exception {
    return mapping.findForward(SUCCESS);
}
Notice the definition of SUCCESS, listed beneath the LoginAction class declaration:private final static String SUCCESS = "success";Currently, the
mapping.findForward the method is set to unconditionally forward any request
            to an output view called success. This is not really desirable; you want to first
            perform some sort of validation on the incoming data to determine whether to send the success
            view, or any different view.Accessing Bean Data and Preparing a Forwarding Condition
- Type in the following code within the body of the executemethod:// extract user data LoginForm formBean = (LoginForm)form; String name = formBean.getName(); String email = formBean.getEmail(); In order to use the incoming form data, you need to takeexecute'sActionFormargument and cast it asLoginForm, then apply the getter methods that you created earlier.
- Type in the following conditional clause to perform validation on the incoming data:
// perform validation if ((name == null) || // name parameter does not exist email == null || // email parameter does not exist name.equals("") || // name parameter is empty email.indexOf("@") == -1) { // email lacks '@' return mapping.findForward(FAILURE); }At this stage, theexecutethe method should look as follows:public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { // extract user data LoginForm formBean = (LoginForm) form; String name = formBean.getName(); String email = formBean.getEmail(); // perform validation if ((name == null) || // name parameter does not exist email == null || // email parameter does not exist name.equals("") || // name parameter is empty email.indexOf("@") == -1) { // email lacks '@' return mapping.findForward(FAILURE); } return mapping.findForward(SUCCESS); }
- Add a declaration for FAILUREto theLoginActionclass (changes in bold):private final static String SUCCESS = "success"; private final static String FAILURE = "failure"; 
execute method forwards the request to the success
                view if the user provides an entry for both name and email fields,
                and the email entered contains an '@' sign. Otherwise, the failure the view is forwarded.
                As will be demonstrated below in Adding forward Entries to struts-config.xml,
                you can set the failure view to point back to the form page, so that the user
                has another chance to enter data in the correct format.Setting Up an Error Message
If the login form is returned, it would be good to inform the user that validation failed. You can accomplish this by adding anerror the field in the form bean, and an appropriate
                <bean:write> tag to the form in login.jsp. Finally, in the Action
                object set the error message to be displayed in the event that the failure the view is chosen.- Open LoginFormand add anerrorfield to the class:// error message private String error; 
- Add a getter method and a setter method for error, as demonstrated above.
- Modify the setter method so that it appears as follows:
public void setError() { this.error = "<span style='color:red'>Please provide valid entries for both fields</span>"; } 
- Open login.jspand make the following changes:<html:form action="/login"> <table border="0"> <tbody> <tr> <td colspan="2"> <bean:write name="LoginForm"property="error" filter="false"/>  </td> </tr> <tr> <td>Enter your name:</td> <td><html:text property="name" /></td> </tr>
- In LoginAction, within theifconditional clause, add a statement to set the error message before forwarding thefailurecondition (changes in bold):if ((name == null) || // name parameter does not exist email == null || // email parameter does not exist name.equals("") || // name parameter is empty email.indexOf("@") == -1) { // email lacks '@' formBean.setError(); return mapping.findForward(FAILURE); }
LoginAction the class should now appear as follows:public class LoginAction extends org.apache.struts.action.Action {
    private final static String SUCCESS = "success";
    private final static String FAILURE = "failure";
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        // extract user data
        LoginForm formBean = (LoginForm)form;
        String name = formBean.getName();
        String email = formBean.getEmail();
        // perform validation
        if ((name == null) ||             // name parameter does not exist
            email == null  ||             // email parameter does not exist
            name.equals("") ||            // name parameter is empty
            email.indexOf("@") == -1) {   // email lacks '@'
            formBean.setError();
            return mapping.findForward(FAILURE);
        }
        return mapping.findForward(SUCCESS);
    }
}
Adding forward Entries to struts-config.xml
In order for the application to match JSP pages with forwarding conditions returned by LoginAction's
            execute the method, you need to add forward entries to the struts-config.xml
            file.- Open struts-config.xmlin the Source Editor, right-click anywhere in theactionentry forLoginForm, and choose Struts > Add Forward.
 
- In the Add Forward dialog box, type successin forwarding Name. Enter the path tosuccess.jspin the Resource File field (i.e.,/WEB-INF/success.jsp). The dialog box should now look as follows:
 
 Click Add. Note that the followingforwardentry was added tostruts-config.xml(changes in bold):<action name="LoginForm" path="/login" scope="request" type="com.myapp.struts.LoginAction" validate="false"> <forward name="success.jsp" path="/WEB-INF/success.jsp"/> </action>
- Perform the same action to add a forward entry for failure. Set the Resource File path to/login.jsp. The followingforwardentry is added tostruts-config.xml(changes in bold):<forward name="success" path="/WEB-INF/success.jsp"/> <forward name="failure" path="/login.jsp"/> 
Configuring and Running the Application
The IDE uses an Ant build script to build and run your web application. The IDE generated the build script when you created the project, basing it on the options you entered in the New Project wizard. Before you build and run the application, you need to set the application's default entry point tologin.jsp. Optionally, you can also add a simple stylesheet
            to the project.Setting the Welcome Page
- In the Projects window, double-click the web.xmldeployment descriptor. The tabs listed along the top of the Source Editor provide you with an interface to theweb.xmlfile. Click on the Pages tab. In the Welcome Files field, enterlogin.jsp.
 
 Now click on the XML tab to view the file. Note thatlogin.jspis now listed in thewelcome-fileentry:<welcome-file>login.jsp</welcome-file> 
Attaching a Stylesheet
- Add a simple stylesheet to the project. One easy way to do this is by saving this sample stylesheet to your computer. Copy the file (Ctrl-C), then in the IDE, select the Web Pages node in the Projects window and press Ctrl-V). The file is added to your project.
- Link the stylesheet to your JSP pages by adding a reference between the <head>tags of bothlogin.jspandsuccess.jsp:<link rel="stylesheet" type="text/css" href="stylesheet.css"> 
Running the Application
- In the Projects window, right-click the project node and choose Run. The IDE builds the
                web application and deploys it, using the server you specified when creating the project.
                The browser opens and displays the login.jsppage. Type in some data that should fail validation, i.e., either leave either field blank or enter an email address with a missing '@' sign:
 
 When you click Login, the login form page redisplays, containing an error message:
 
 Try entering data that should pass validation. Upon clicking Login, you are presented with the success page:
 
