LESSON I - Introduction - Your First Struts App

来源:互联网 发布:java 半角转全角处理 编辑:程序博客网 时间:2024/04/25 15:35
The application you are going to create mimics entering an employee into a database. The user will be required to enter an employee's name and age.

Concepts introduced in Lesson I:

Setting up your environment
Data Transfer Object
ActionForm
web.xml
struts-config.xml
ApplicationResources.properties
BeanUtils
Tag usage

The steps (see left menu) in this lesson will walk you through building all of the necessary components for this small application. If you want to download the complete application you can do so. (You should be able to plop this war file into your application server webapps directory and it should work fine).
Download rr_lesson_1 application.war

Begin lesson now by clicking START.

LESSON I - 1 - Install Tomcat

Download and install the latest stable version of Tomcat:

You can download Tomcat here: http://jakarta.apache.org/site/binindex.cgi

Setting up Tomcat is not difficult but is out of the scope of this tutorial. (Most of these basic tutorials should run fine on Tomcat versions 4.0.x and above or any other decent application server).

NEXT >

LESSON I - 2 - Create Application Directory

Create the web application directory:

Create the directory "rr_lesson_1"in the {tomcat}/webapps/ directory
(where {tomcat} equals the root directory of your Tomcat installation).

The following directory structure should look like:
webapps   |   |   rr_lesson_1       |       |        --- WEB-INF              |              |--- classes              |      |              |       --- net              |            |              |             -- reumann              |--- lib              |               --- src                    |                     --- net                          |                           -- reumann


< PREV ???? NEXT >

?

LESSON I - 3 - Add Struts Files

Download & Install Struts:

Download the latest version of Struts here: http://www.apache.org/dist/jakarta/struts/binaries/ (binary version)

The lesson assumes you are are using Struts 1.1. The directory structure at the time you are reading this may be different than the above binary you download. (If you can not seem to find the files you need, you can just use the files that come with the download of this lesson application in the war file).

After downloading your Struts archive, extract it into a directory of your choosing (preferably outside of the entire Tomcat directory).

Copy .tld files from struts into rr_lesson_1 application:

Go to the {StrutsDirectory}/contrib/struts-el/lib directory and copy the following .tld files into the rr_lesson_1/WEB-INF directory:

c.tld
struts-bean-el.tld
struts-html-el.tld
struts-logic-el.tld



Copy .jar files from struts into rr_lesson_1 application:

Next copy the following .jar files from {StrutsDirectory}/contrib/struts-el/lib into rr_lesson_1/WEB-INF/lib directory:

commons-beanutils.jar
commons-collections.jar
commons-digester.jar
commons-logging.jar
jstl.jar
standard.jar
struts-el.jar
struts.jar



(Note we are using the tld files and jars in the contributed struts-el directory since this will help us to use the standard JSTL tags whenever possible).

< PREV ???? NEXT >

LESSON I - 4 - Create Data Transfer Object

Since we are dealing with an Employee that we want to insert, we need a way to store information about this Employee that we could hand off to a business object (the model layer of MVC). Our model layer will be responsible for doing the actual insert. So the first thing we need is a class representing our employee. We'll make a bean that has just a couple of fields and appropriate get and set methods.

Since this object will transfer stored information from one part of our application to another it is called a Data Transfer Object (or often Value Object).

Create EmployeeDTO:

package net.reumann;public class EmployeeDTO {    private String name;    private int age;        public void setName(String name) {        this.name = name;    }    public void setAge(int age) {        this.age = age;    }    public String getName() {        return name;    }    public int getAge() {        return age;    }}


< PREV ???? NEXT >

LESSON I - 5 - Create Business Service

Probably the most complex part of your web application will be dealing with the business logic. Since this area is beyond solutions that Struts provides, we aren't going to get into that area in this lesson. However, we need to create at least one object that will act as a transition object to the model layer of our MVC application.

We will create an EmployeeService class to handle the small amount of business logic we have. In a more complex set up you might have a factory that returns an EmployeeService implementation of a Service interface.

Create EmloyeeService:

package net.reumann;public class EmployeeService {    public EmployeeDTO insertEmployee( EmployeeDTO employee ) {        //in real life call other business classes to do insert        //ie:         //EmployeeDAO.insertEmployee( employee );        return employee;    }}


Note: we do not have to return the EmployeeDTO back. You might want to return a boolean or some other variable instead that indicates success. Failure should throw an Exception and our insertEmployee method in real life would probably handle some sort of DAOException if it were thrown.

< PREV ???? NEXT >

LESSON I - 6 - Create ActionForm

We have an EmployeeDTO object to hold the employee information that will get passed to our EmployeeService object which is responsible for calling some other business model components to actually do the insert into the database. Remember, though, our DTO is a bean that holds the correct data types of the information that we care about inserting (for example type int for age). Information that the user inputs on JSP form will always be submitted as String parameters in the request. We may also want to validate the information that is submitted in the form. Struts uses ActionForm objects to hold the JSP form data that is sumbitted. (They could also be used for displaying results back on a page, although this is a less common function). The ActionForm should contain String fields representing the properties in the EmployeeDTO.

Create EmployeeForm:

package net.reumann;import org.apache.struts.action.ActionForm;import org.apache.struts.action.ActionMapping; public class EmployeeForm extends ActionForm  {     private String name;    private String age;        public void setName(String name) {        this.name = name;    }    public void setAge(String age) {        this.age = age;    }    public String getName() {        return name;    }    public String getAge() {        return age;    }}


< PREV ???? NEXT >

LESSON I - 7 - Create web.xml

Normally you would probably create this file first but we are doing it here just to show how it fits in with the struts application as a whole.

We just created our EmployeeForm which will end up holding the fields that the user enters on a JSP form, but before we create the JSP page, there are few things to do first. Since we are using an MVC architecture all requests will pass through a controller. The main controller of Struts is the org.apache.struts.action.ActionServlet. A lot takes place when this controller servlet is called. ( Chuck Cavaness' book 'Programming Jakarta Struts' explains this process well in Chapter 5 ). The basic thing to understand at this point is that all your requests will pass to this servlet and eventually mappings that you set up will be called as a result of requests passed to this controller servlet. This servlet is the main thing that we need to declare in your application's web.xml file.

Create the web.xml file in the rr_lesson_1/WEB-INF directory:

          action    org.apache.struts.action.ActionServlet          application      ApplicationResources              config      /WEB-INF/struts-config.xml              debug      3              detail      3        1             action    /do/*          index.jsp            struts/bean-el    /WEB-INF/struts-bean-el.tld        struts/html-el    /WEB-INF/struts-html-el.tld        struts/logic-el    /WEB-INF/struts-logic-el.tld          jstl/c    /WEB-INF/c.tld     


Note: Any URI call to /do/* will send the request to this ActionServlet. (You don't have to use /do/*, you can use whatever you want- ie. /*.action, /*.do, etc). Also note that all of the tags we will use are defined in this file as well.

< PREV ???? NEXT >

LESSON I - 8 - Create struts-config.xml

If you look at the ActionServlet declaration in the web.xml file you see the config parameter "struts-config.xml." The controller ActionServlet will use this struts-config file to determine all kinds of important things. This struts-config.xml file will be the 'road map' of our application. This file will tell our requests where to go (usually an Action class), what Form beans to use, and where to go after the request submits. Don't worry about understanding all the parts of this file right now. You will understand more as you go along.

Create struts-config.xml file in rr_lesson_1/WEB-INF directory:

                                                                            


Some points about the struts-config.xml file:

Notice we defined a form-bean definition for the EmployeeForm (ActionForm) that we created in Step 6. The name property was called "employeeForm." Now look at our the action-mapping for the path "/insertEmployee" in the struts-config file. When a user submits a form (or link) with the path /do/insertEmployee the request will be sent to the ActionServlet which we defined in the web.xml. Eventually a RequestProcessor object called from the ActionServlet will find this mapping and send the request to the type of Action class that we define in this mapping. (You'll learn about the Action class next). This Action class object is defined where you see type="net.reumann.InsertEmployeeAction". Our request will go to this class and when it exists you will see it try to get the 'forward' mapping with the name "success" and will forward to the page defined in our mapping (/confirmation.jsp). The last thing to note is the definition of the message-resources. The ApplicationResources value refers to a properties file (ApplicationResources.properties) that we are going to add to our classes directory. This file will hold key/value pairs that will save us from having to hard code information directly in our JSPs.

< PREV ???? NEXT >

LESSON I - 9 - Create Action class

The main classes used in the Struts framework are those of org.apache.struts.action.Action. The Action classes are the true concrete bridges bewteen the client's request and the business layer. For the most part, each Action class will handle one particular type of business operation the client wants to perform (in this case the insert of an Employee).

Notice our action mapping in the struts-config file:


The path attribute will correspond to the action we will define for our JSP form. When the form is submitted with this action path our request will make it to InsertEmployeeAction. When it exits the InsertEmployeeAction it will forward to confirmation.jsp by looking up the foward name "success."

Create InsertEmployeeAction:

package net.reumann;import org.apache.struts.action.Action;import org.apache.struts.action.ActionForward;import org.apache.struts.action.ActionMapping;import org.apache.struts.action.ActionForm;import org.apache.commons.beanutils.BeanUtils;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public final class InsertEmployeeAction extends Action {     public ActionForward execute(ActionMapping mapping,                                 ActionForm form,                                 HttpServletRequest request,                                 HttpServletResponse response)        throws Exception {        EmployeeService service = new EmployeeService();        EmployeeForm employeeForm = (EmployeeForm) form;        EmployeeDTO employeeDTO = new EmployeeDTO();        BeanUtils.copyProperties( employeeDTO, employeeForm );        service.insertEmployee( employeeDTO );        request.setAttribute("employee",employeeDTO);        return (mapping.findForward("success"));    }}


The Action class has one method to worry about "execute(..)." When we submit our JSP page the behind the scenes Struts stuff (Action Servlet and RequestProcessor) will find this Action class that we associated with the /insertEmployee action in the struts-config.xml file and the execute method will be called. Since the /insertEmployee action uses the EmployeeForm the InsertEmployeeAction will have this form bean of type ActionForm, so we first cast this into type EmployeeForm. Now we want to get the information in our EmployeeForm into the EmployeeDTO so we can pass that off to our Model layer. We created an instance of EmployeeDTO and then, like magic, we can use BeanUtils (from the Jakarta commons package) to transfer the data from EmployeeForm into the EmployeeDTO with one easy line: BeanUtils.copyProperties( employeeDTO, employeeForm ). This is a HUGE time saver, for if you are not going to use BeanUtils (or PropertyUtils) than you would normally build a helper class to do all the get and set stuff and all the data type conversions (a real pain, especially for large beans).

After copyProperties() the now populated EmployeeDTO is passed off to the service object and the insert would be done. (We'll learn more in a later lesson about dealing with Exceptions that your model/business objects may throw). After the insert is done the EmployeeDTO is stuck into request scope so we could use the employee information for display purposes.

The last thing to notice is that we need to return an ActionForward object which will tell our behind the scenes controller where we should forward to when the execute method is completed. In this case I want to forward to whatever I defined as "success" in my struts-config mapping for this action. Calling mapping.findFoward("success") will return an ActionForward object based on looking up the foward pararmeter in our mapping that matches "success" (in this case /confirmation.jsp). (Note: Rather than hard-code the word "success" here you should create a Constants class/interface that has these commonly used String variables).

< PREV ???? NEXT >

LESSON I - 10 - Create Resources File

In the struts-config.xml file there is the definition:


This tells our application that we are using a properties file called "ApplicationResources.properties" which is located in our WEB-INF/classes directory. (If you aren't using Ant, or some other kind of build tool, you might want to put this same file in you src directory as well, since your IDE might delete classes and rebuild from src.) This file will be use mostly to hold display items for our JSPs. It allows us to not have to hard code titles, error messages, button names, etc. We could even have different files based on different languages. This file will normally contain a lot of information, and you will see why in further lessons.

Create ApplicationResources.properties in rr_lesson_1/WEB-INF/classes:

#-- titles --title.employeeApp=EMPLOYEE APPLICATIONtitle.employee.employeeform=EMPLOYEE FORMtitle.employee.insert.confirmation=EMPLOYEE INSERT CONFIRMATION#-- buttons --button.submit=SUBMIT



< PREV ???? NEXT >

LESSON I - 12 - Create index.jsp

Create index.jsp in rr_lesson_1/ :

<%@ taglib uri="struts/bean-el" prefix="bean" %><%@ taglib uri="struts/html-el" prefix="html" %>" rel="stylesheet" type="text/css"><bean:message key="title.employeeApp"/>


Add An Employee


In this application, this is the first page the user will see. Notice the taglibs needed are defined at the top. The first html:rewrite tag will prepend our webapp context (in this case rr_lesson_1) to /rr.css. This is a useful tag since it enables us to not have to hard code your webapp name in your code. Next the bean:message tag is used to look up the key 'title' in the ApplicationResources.properties file and write that to the page. Then notice the use of the html:link page. The html:link tag is useful since it will write out an tag using the correct path to your root directory added to the beginning of your link. It also appends a sessionID in case the user has cookies disabled. Also notice that the link is calling /do/setupEmployeeForm. This will actually forward us through the controller servlet (since it's mapped to /do/*). The controller knows where to forward to when the link is clicked based on the mapping in the struts-config file:



Clicking on the link will thus forward us to the employeeForm.jsp page.

(Note: Even better than using html:link page="" is using html:link forward="". Using html:link forward="someForward" you can set up the actual /do/whatever mapping that "someForward" will call in the strutsConfig file ).

< PREV ???? NEXT >

LESSON I - 13 - Create employeeForm.jsp

Create employeeForm.jsp in rr_lesson_1/ :

<%@ taglib uri="struts/bean-el" prefix="bean" %><%@ taglib uri="struts/html-el" prefix="html" %>" rel="stylesheet" type="text/css"><bean:message key="title.employee.employeeform"/>

Name: Age:


Here you see the use of html:form tag. The form tag will end up displaying:



The name of the form- "employeeForm" comes from the name of the formBean that we associated in the mapping for /insertEmployee in our struts-config.xml file (name="employeeForm"). All you have to worry about is using the correct action when you use the tag and the rest is handled by Struts. Using focus="name" will write some javascript to the page to have our form begin with focus on the name field (name in this case refers to the "name" field in the actual EmployeeForm bean). Struts makes extenstive use of form field tags like In our example Struts took care of putting the EmployeeForm we defined in our struts-config.xml mapping into request scope and the html:text tags will look for the fields mentioned as property values in the EmployeeForm and will set them up as the name values for our input buttons. If there are any values associated with the fields in the form it will also display that value. If our EmployeeForm had an initial age value of "33" then would end up displaying in the source as .

< PREV ???? NEXT >

LESSON I - 14 - Create confirmation.jsp

Create confirmation.jsp in rr_lesson_1/ :

<%@ taglib uri="struts/bean-el" prefix="bean" %><%@ taglib uri="struts/html-el" prefix="html" %><%@ taglib uri="jstl/c" prefix="c" %><bean:message key="title.employee.insert.confirmation"/>" rel="stylesheet" type="text/css">


SUCCESSFUL INSERT OF EMPLOYEE

NAME:
AGE:


This is the page our Action will forward to after leaving the InsertEmployeeAction. Remember in the execute method we put an EmployeeDTO into request scope. Using the JSTL c tag we can display the properties of this object which was placed in request scope.

This wraps up Lesson I. I hope you found it helpful. Please send any comments or suggestions to struts@reumann.net

< PREV

原创粉丝点击