Open SourceDeveloping a Struts Application with the NetBeans IDE

Developing a Struts Application with the NetBeans IDE

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

You know Struts is one of the most popular free, open-source frameworks for creating Java Web applications. You know it’s based on the Model-View-Controller (MVC) architecture to separate concerns in an application. But did you know that Struts has been integrated into the NetBeans IDE since version 6.7? The current version (as of this writing) is version 6.9 and the example in this article uses NetBeans 6.8.

If you were unaware of the Struts/NetBeans IDE integration, this article will walk you through the NetBeans interfaces and wizards for developing a simple Struts login application. Before starting, you need to download NetBeans 6.8 or higher (try the Java Web and EE release). Remember that you do not need to explicitly download Struts, because Struts 1.3.8 is already bundled in the NetBeans IDE.

Creating the Struts Application Stub in NetBeans Style

After you start NetBeans, you can create a Struts application stub with a few simple steps as follows (NetBeans automatically generates this application, which you can consider the starting point for any Struts application):

  1. Choose File | New Project.
  2. Under Categories, select Web. Under Projects, select Web Application and click Next (see Figure 1).

  3. On this page, under the Project Name section, type login and select the location of the project. Click Next.
  4. In the next panel, you can choose the server that will host this application, the Java EE version and the context path. For this example, choose GlassFish v3 server, Java EE 6 Web and do not modify the default context path. Click Next.
  5. In the Frameworks panel, select Struts 1.3.8 (see Figure 2). This is a major step because you indicate to NetBeans your intention to use Struts. Click Finish.

Below the Frameworks panel, you will find the following set of configuration settings for Struts (do not modify any):

  • Action Servlet Name: indicates the name of the Struts action servlet (This is mapped in web.xml descriptor.)
  • Action URL Pattern: represents the incoming requests, which are mapped to the Struts action controller (By default, only the *.do pattern is mapped in the deployment descriptor.)
  • Application Resource: in this section, you may specify the resource bundle, which will be used in the struts-config.xml descriptor
  • Add Struts TLDs: lets you generate tag library descriptors for the Struts tag libraries

What the Generated Stub Contains?

After the stub it is generated, you should see the welcomeStruts.jsp page in the NetBeans editor. Before modifying this page, consider what else was added/generated in your Struts application stub. For starters, notice that the Struts libraries were added in the project under the Libraries folder of the login project (see this in the Projects tab). Going further, you should notice the content of the Configuration Files folder, which contains the Struts-specific descriptors (struts-config.xml, tiles-defs.xml, validation.xml, validator-rules.xml) and the application deployment descriptor (web.xml) — all of them were generated with minimal information but enough to have a functional Struts application. Take the time to open these files and explore their contents. Finally, notice the two JSP pages: index.jsp and welcomeStruts.jsp. The former contains a simple JSP-style redirect to the latter, which displays a simple welcome message.

Creating the Login.jsp Page from WelcomeStruts.jsp

As stated in the introduction, you will develop a simple login application. Now, that you have the stub it is time to go further and start developing the login.jsp page, which will render the login form. For this, you can create a new JSP page and delete the welcomeStruts.jsp, or you can try to modify this existing page. First you will employ the second option, and in the next section you will develop a JSP page from scratch.

Here are the steps of transforming the welcomeStruts.jsp into login.jsp:

  1. Rename the welcomeStruts.jsp page by right clicking on its name in the Projects tab (under the Web Pages folder) and choose Rename. Type the new name without an extension and press OK.
  2. Go to index.jsp and modify the redirect to login.jsp like this:
    <jsp:forward page="Login.do"/>
  3. Open the struts-config.xml file and navigate to the Global Forwards section. Notice that you can navigate to any section from this descriptor by using the NetBeans Navigator, which automatically appears by default in the lower-lefthand corner, like in Figure 3.



    Figure 3. NetBeans IDE Navigator Panel

  4. Modify the single global forward like this:

    <global-forwards>
       <forward name="login" path="/Login.do"/>
    </global-forwards>
  5. Navigate to the Action Mappings section and modify the single action like this:

    <action-mappings>
       <action path="/Login" forward="/login.jsp"/>
     </action-mappings>

Now that you have completed the renaming and fixed the navigation to your login.jsp page, it’s time to add some real content to it. In this case, you will render a simple login form mapped in a simple HTML table (note that you can speed up the development of this table by using the NetBeans Palette — if it is not clear that you can activate it from the Window menu).

When you type in the Source Editor, NetBeans 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. Figure 4 presents a simple capture of inserting a Struts form into your page.

Now, the login.jsp page code looks like this (typical Struts application code):

<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>

<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html" %>

<html:html>
 <head>
     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
     <title>Login page</title>        
 </head>
 <body style="background-color: white">

     <html:form action="/login">
         <html:errors property="wrongemail" />
         <html:errors property="wrongpass" />
         <table border="1">
             <thead>
                 <tr>
                     <th>Login to your site</th>
                     <th></th>
                 </tr>
             </thead>
             <tbody>
                 <tr>
                     <td>Email:</td>
                     <td><html:text property="email" /></td>
                 </tr>
                 <tr>
                     <td>Password:</td>
                     <td><html:password property="pass" /></td>
                 </tr>
             </tbody>
         </table>
         <html:submit value="Login" />
     </html:form>

 </body>
</html:html>

Creating the Success.jsp Page

When the user has successfully logged in, you must redirect the application flow to the requested page. In this case, you render a success.jsp page, which is a very simple confirmation of the login credentials. Follow these steps:

  1. Create a new JSP page. In the Projects tab, expand the login project and right-click on the Web Pages folder. Select the New | JSP ... option from the contextual menu and type “success” in the File Name section of the New JSP File wizard. Press Finish.
  2. 2.

  3. Modify the generated code like below (remember to explore the NetBeans Palette, code completion for Struts tags and Struts Javadoc):
    <%@page contentType="text/html" pageEncoding="UTF-8"%>
    
    <%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %>
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
    
    <html>
     <head>
         <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
         <title>Login Successfully</title>
     </head>
     <body>
         <h1>Login Successfully Done</h1>
         <p>Email: <bean:write name="LoginActionForm" property="email" />.</p>
         <p>Password: <bean:write name="LoginActionForm" property="pass" />.</p>
     </body>
    </html>

Creating the Failure.jsp Page

When the provided credentials are wrong, you redirect the application flow to a page called failure.jsp. This is generated in the same manner as success.jsp and it looks like this:

<%@page contentType="text/html" pageEncoding="UTF-8"%>

<%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

<html>
 <head>
     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
     <title>Login Failure</title>
 </head>
 <body>
     <h1>Login Failure</h1>
     <p>Email: <bean:write name="LoginActionForm" property="email" />.</p>
     <p>Password: <bean:write name="LoginActionForm" property="pass" />.</p>
 </body>
</html>

Creating an ActionForm Bean

A Struts ActionForm bean is perfect for storing the provided credentials between requests (or any data provided through a form). Since you need to store the email and the password, which are two strings, your bean will be pretty short and simple (note that in Struts parlance, “an ActionForm is a JavaBean optionally associated with one or more ActionMappings. Such a bean will have had its properties initialized from the corresponding request parameters before the corresponding Action.execute method is called.“). Here are the steps for creating it:

  1. In the Projects tab, right-click on the login project and select New | Other ... from the contextual menu.
  2. In the New File wizard’s Categories list, select the Struts category, and from the File Types list, select the Struts ActionForm Bean type and press Next (see Figure 5).
  3. Now you have to type a name for the new action form. For example, type “LoginActionForm” in the Class Name section. Also, choose the com.myapp.struts package from the Package list (see Figure 6). Click Finish.

  4. When you press the Finish button, NetBeans will generate the new action form for you and display it in the Source Editor. By default, this class provides it with a String called name and an int called number, along with getter/setter methods for them called delete all, because you need to add the email and the password! Also, if you check the struts-config.xml, you can see the new form bean added under the Form Beans section:
    <form-bean name="LoginActionForm" type="com.myapp.struts.LoginActionForm"/>
  5. In the LoginActionForm, add two properties like this:
    private String email;
    private String pass;
  6. Add getter/setter methods for these two properties. Go below this code and right-click in an empty spot. From the contextual menu, select Insert Code ... and Getter and Setter .... In the Generate Getters and Setters window, select the two properties and press Generate. Now, you should see the corresponding methods in your code.

For now, comment the validate method and read further. You will deal with this method in validation section.

Implementing the Business Logic in Struts Style

Your next task is to generate an Action class and implement the execute method. In Struts parlance: “when a request is received, the Controller invokes an Action class. The Action class consults with the Model (or, preferably, a Facade representing your Model) to examine or update the application’s state.” The execute method is the “brain” of your application, because here you tell the application what to do.

For starters, follow the steps below to generate an Action stub:

  1. In the Projects tab, right-click on the login project and select New | Other ... from the contextual menu.
  2. In the New File wizard’s Categories list, select the Struts category and from the File Types list, select Struts Action type and press Next.
  3. Now you have to type a name for the new action. For example, type LoginAction in the Class Name section. Also, choose the com.myapp.struts package from the Package.
  4. Type /login in the Action Path section. This value must be the same as the one provided in the action attribute of the <html:form> tag in login.jsp. Click Next.
  5. In this window, you have to associate the Action with an ActionForm. By default, the IDE did that for you, but notice that this can be accomplished manually by selecting the corresponding ActionForm from the list ActionForm Bean Name.
  6. In addition:
    • Type /login.jsp for the Input Resource field, or use the Browse button.
    • Set the Scope to Request.
  7. Click Finish.

Now, you should see the generated code of your action in the Source Editor. If you look in struts-config.xml, you will notice the new added entry under Action Mappings, like this:

<action input="/login.jsp" name="LoginActionForm" path="/login" scope="request" type="com.myapp.struts.LoginAction"/>

Going further, you must add a behavior to the execute method. You have a simple scenario: the login credentials should be an email address of “admin@yahoo.com” and a password of “admin.” If the provided credentials match these, then you forward the user to success.jsp, if not to failure.jsp. The code looks like this after you have used the generated code and added the needed lines:

/* forward name="success" path="" */
 private static final String SUCCESS = "success";
 private static final String FAILURE = "failure";
 
 /**
  * This is the action called from the Struts framework.
  * @param mapping The ActionMapping used to select this instance.
  * @param form The optional ActionForm bean for this request.
  * @param request The HTTP Request you are processing.
  * @param response The HTTP Response you are processing.
  * @throws java.lang.Exception
  * @return
  */
 @Override
 public ActionForward execute(ActionMapping mapping, ActionForm form,
         HttpServletRequest request, HttpServletResponse response)
         throws Exception {
     
     LoginActionForm data = (LoginActionForm)form;
     
     String email = data.getEmail();
     String pass = data.getPass();
     
     if ((email.equals("admin@yahoo.com")) && (pass.equals("admin"))){
         return mapping.findForward(SUCCESS);
     } else {
         return mapping.findForward(FAILURE);
     }
 }

Configure the Forwards Entries

As you can see, your action class contains two forwarding conditions, SUCCESS and FAILURE. In this section, you configure these forwards in the struts-config.xml file as follows (Without these configurations, Struts will not know what JSP pages to associate to the forwarding conditions. You know that SUCCESS should be associated to success.jsp and FAILURE to failure.jsp, and now Struts will also know that.):

  1. In struts-config.xml, right-click anywhere in the action entry for LoginActionForm and choose Struts | Add Forward from the contextual menu (notice that in this contextual menu you have an entire set of Struts components that can be added through the IDE wizards).
  2. In the Forward Name section, type “success.” In the Resource File, type /success.jsp or use the Browse button to navigate to this page (see Figure 7). Click Add.

Repeat this process for FAILURE, but select the /failure.jsp page and type “failure” in the Forward Name section. Now, in struts-config.xml, you should have this:

<action input="/login.jsp" name="LoginActionForm" 
     path="/login" scope="request" type="com.myapp.struts.LoginAction">
  <forward name="success" path="/success.jsp"/>
  <forward name="failure" path="/failure.jsp"/>
</action>

Implementing the Validate Method of the LoginActionForm

Bottom of LoginActionForm, you have a validate method generated by the IDE (you will find a comment there, which you have to uncomment first). This method allows you to put more reusable validation in ActionForm and return non-empty ActionErrors from validate to trigger redisplay of input data.

Author Note: Remember that Struts has powerful support for validating dates. Check out the specialized tutorials for more information.

Next, you add a basic validation over the provided login credentials:

@Override
 public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
     ActionErrors errors = new ActionErrors();
     if (getEmail() == null || getEmail().length() < 6) {
         errors.add("wrongemail", new ActionMessage("errors.email", "This email"));
     }
     if (getPass() == null || getPass().length() < 5) {
         errors.add("wrongpass", new ActionMessage("errors.minlength", "Password", "6"));
     }
     return errors;
 }

You’re done! Now you can test the application and see how it works. Press the Run Main Project button over the IDE main toolbar! In Figure 8, you can see a simple test of the validation process.



Figure 8. Running the Login Application Sample

Conclusion

The NetBeans IDE provides great support for developing Struts applications, and it is a pleasure to work with in the production stage. When you discover and utilize the other facilities of NetBeans, you will have the perfect IDE for developing amazing Java-based Web applications.

Code Download

  • StrutsAppNetBeans_login.zip
  • About the Author

    Anghel Leonard is a senior Java developer with more than 13 years of experience in Java SE, Java EE, and the related frameworks. He has written and published dozens of articles about Java technologies and two books about XML and Java (one for beginners and one for experts).

    Get the Free Newsletter!

    Subscribe to Developer Insider for top news, trends & analysis

    Latest Posts

    Related Stories