facebook

Creating a Web Application with Struts 1.x

This tutorial walks you through the development and testing of a simple Struts login page example. Struts, which has a similar framework as JSF, allows you to organize resources as the first phase of development. In this tutorial, you will learn how to:

  • Create a Web project with the Struts 1 facet
  • Create JSP pages with actions
  • Run and test the application

This feature is available in MyEclipse.

1. Create a New Struts 1 Project

  1. Select File>New>Web Project.
  2. Type StrutsLoginDemo in the Project name field and click Finish to accept the defaults. 

    strutsnewwebproject
    Creating a new Web project
  3. Right-click the project, and select Configure Facets…>Install Apache Struts (1.x) Facet This menu option was updated in MyEclipse 2017. For prior versions, click here. .
  4. Accept the default values for the purposes of this tutorial, and click Finish.

    Note: On page 2 of the wizard, you might want to change the base package for new classes to reflect your desired location.

    strutsinstallfacet
    Configuring Struts capabilities

The project structure looks like the following:

strutsexplorer
Project structure

2. Create the Login Success Feedback Page

To begin the construction of the demo application, first focus on creating the JSP pages. Because the demo application mimics a login screen on a website, only two JSP pages are required: userLogin.jsp and userLoginSuccess.jsp. As with most Struts apps, if something goes wrong during the login, the application returns the user to the userLogin.jsp page and displays an error, which is why this application doesn’t need a loginUserFailure.jsp page.

Start by creating the userLoginSuccess.jsp page first, although this might seem backwards. By creating the last page first, you can use the Form, Action, and JSP wizard to create the first JSP page along with the related Action and ActionForm.

  1. In the Explorer, expand StrutsLoginDemo>WebRoot>WEB-INF, and double-click struts-config.xml to open the Designer.
  2. Click the JSP palette tool, and then click the canvas.

    mestrutsdesignco
    Creating a JSP using the Designer
  3. Type userLoginSuccess.jsp in the File Name field, select Standard JSP using Struts 1.2/1.3 from the Template to use drop-down, and click Finish.

    strutsnewjsp
    Configuring the new JSP
  4. Double-click the resource on the canvas to open the file in the JSP editor.

    mestrutsopeneditorco
    Struts Designer showing the JSP page
  5. Copy the following snippet, select all the code in the userLoginSuccess.jsp page, and paste. Press CTRL+S to save the file.
    <%@ page language="java" pageEncoding="ISO-8859-1"%>
    <%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %>
    <%@ taglib uri="http://struts.apache.org/tags-html" prefix="html" %>
    <%@ taglib uri="http://struts.apache.org/tags-logic" prefix="logic" %>
    <%@ taglib uri="http://struts.apache.org/tags-tiles" prefix="tiles" %>
    <%@ taglib uri="http://struts.apache.org/tags-nested" prefix="nested" %>
     <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
       <html:html > 
           <head> 
              <title>My Struts 'userLoginSuccess.jsp' ending page</title> 
           </head>
           <body> 
              Hello <bean:write name="userName" scope="request" />, you successfully logged in! 
           </body> 
     </html:html>

    The important thing to note is the contents of the <body> tag, which prints the value of the variable userName that is stored in the request scope of the application. So, in the action you create later, you need to place an attribute by the name of userName in the request scope.

3. Create the User Login Page

You still need to create the userLogin.jsp page, the ActionForm, and the Action, which can streamlined considerably by way of the New Form and New Form, Action and JSP wizards.

When creating the userLogin.jsp page, you need to consider the fields you want to display on this page and map those fields to the respective ActionForm. The form stores the values and ensures they get passed to the proper Action. Both of the MyEclipse wizards mentioned above, when generating the Form, offer the ability to create a JSP page along with the form. This takes the properties of the Form and generates a JSP page with the form fields ready to use. Because you also want to create an Action to process the login, use the New Form, Action & JSP wizard instead of the New Form wizard.

  1. Right-click the canvas, and select New>New Form, Action and JSP.
  2. Type userLogin in the Use case field. This helps the wizard fill in default values.

    strutsnewform
    Creating the new form
  3. Click Add to add two form properties: userName and password. When adding the password, select password from the JSP input type drop-down.

    strutspasswordproperty
    Adding properties to the form
  4. Click the JSP tab to indicate you want MyEclipse to generate a skeleton JSP page including a form with these values in it.

    strutsnewformwithproperties
    Form properties to be used by the Action form
  5. Select the Create JSP form checkbox, and remove the default /form from the New JSP Path field.

    Note: The default behavior of the wizard is to place generated JSPs into a /form subfolder. For this demo application, we are placing all the JSPs in the webroot instead.

    strutsnewformjsp
    Enable JSP page generation for the form
  6. Click the Methods tab, and deselect all the methods the wizard can auto-generate.

    Note: To keep this demo simple, we won’t generate custom reset or validate methods, but it is generally a good idea to make use of these methods when coding your own application.

    strutsnewformmethods
    Disabling method generation
  7. Click Next. The New Action wizard opens with most values filled in for you.
  8. Click the Forwards tab, and click Add.
  9. Type success in the Name field, type /userLoginSuccess.jsp in the Path field, and click Add. Add another for failure with the path /userLogin.jsp.

    strutsforwardstab
    Action forwards
  10. Click Finish. MyEclipse creates the resources and updates the struts-config.xml file (and Designer) with the new information.

    Note: Some manual layout was done so all the elements of the diagram display clearly in a small screenshot. When you manually layout a diagram, your changes are preserved for future edits.

    strutsdesignerfinish
    Struts Designer displaying the application

    From the design layout, you can see the application starts by displaying the userLogin.jsp page. The login page calls the userLogin action to perform the login operation. If there are validation errors or problems, the userLogin action returns the user to the userLogin.jsp page. However, if the login was successful, the application forwards to the userLoginSuccess.jsp page.
  11. Double-click the userLogin action to open the UserLoginAction.java file. With the application flow defined, you need to add logic to the Action to handle the login procedure.

    When you open the UserLoginAction.java file the first time, the generated code for the execute method throws an exception. Instead, you want to change it to open either the success page or the failure page based on what the user types into the login fields.
  12. Copy the following code, and paste the code into the UserLoginAction.java file, replacing the default public ActionForward method. Press Ctrl+S to save.

     public ActionForward execute( 
         ActionMapping mapping, 
         ActionForm form, 
         HttpServletRequest request, 
         HttpServletResponse response) { 
            UserLoginForm userLoginForm = (UserLoginForm)form;
                if(userLoginForm.getUserName().equals("myeclipse")
                 &&
                 userLoginForm.getPassword().equals("myeclipse")) 
                   { 
                    request.setAttribute("userName",
                    userLoginForm.getUserName()); 
                    return
                    mapping.findForward("success"); 
                   }         
    
                   return mapping.findForward("failure"); 
                  }

    This code checks if the userName and password values are both “myeclipse”. If they are, it stores the userName in the request scope and returns the success forward, so the userLoginSuccess.jsp page can display a personalized message. Otherwise, something went wrong and we return the failure forward. In a real application, you would typically add an ActionMessages or ActionErrors collection back to the request scope before returning a failure forward to explain what caused the error.
  13. Click the file tab at the top of the Designer to display the struts-config.xml file. Press Ctrl+S to save it.

4. Run the Application

  1. Right-click the project, select Run As>MyEclipse Server Application, select MyEclipse Tomcat and click Finish.
  2. When the server starts, its output is directed into the Console view. You can view messages showing server startup and deployment of the application, and the default JSP opens in the web browser.
  3. Change the URL in the address bar to open the userLogin.jsp file – http://localhost:8080/StrutsLoginDemo/userLogin.jsp.

    strutsbrowser
    Application viewed in the browser
  4. Type myeclipse in both fields, and click Submit.

    When you submit the form, the application validates the form and forwards to the successful login page, userLoginSuccess.jsp.

    stutsbrowserresult
    Successful login