Lesson I - Introduction - Your First Struts App

xiaoxiao2021-03-06  109

. The application you are going to create mimics enterual.

Concepts Introduces 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 Tutorialings) 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

?

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} / control / struts-el / lib Into rr_lesson_1 / web-inf / lib DIRECTORY:

Commons-beanutils.jar

Commons-Collects.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 Usever Possible).

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 Offense 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;

}

}

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 are not 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 EMLOYESERVICE:

Package net.reumann;

Public Class EmployeService {

Public Employeedto INSERTEMPLOYEEE (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.

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 EMPLOYEFORM:

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 agec;

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;

}

}

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 : ACTIO n

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 whatver you want- ie. /*.Action, /*.do, ETC). Also Note That All of the tags we will use all defined in this file as well.

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. Do not 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 Now look at our the action-mapping for "employeeForm." 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-reso urces. 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 Create InsertEmployeeAction "success.":

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 {

EmployeService Service = New EmployeService ();

Employeeform Employeeform = (EMPLOYEEFORM) Form;

Employeedto Employeedto = New Employeedto ();

Beanutils.copyProperties (Employeedto, Employeeform);

Service.insertemployee (Employeedto);

Request.setttribute ("Employee", Employeedto);

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 There EXECUTE METHOD IS Completed. In this case I want to forward to whatver I defined as "surcess"

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 tring variables). 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 are not 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 Application

Title.employee.employeeform = Employee Form

Title.employee.Insert.confirmation = Employee Insert Confirmation

# - Buttons -

Button.submit = SUBMIT

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"%>

href = "

"rel =" stylesheet "type =" text / css ">

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: Lin Forward = "SomeForward" you can Set up the actual / do / wherever mapping That "Will Call in the strutsconfig file".

Lesson I - 13 - Create Employeeform.jsp

Create Employeeform.jsp in r_lesson_1 /:

<% @ Taglib Uri = "struts / bean-el" prefix = "bean"%>

<% @ Taglib URI = "Struts / HTML-EL" prefix = "html"%>

href = "

"Rel =" stylesheet "type =" text / css ">

Name:

Age:

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

转载请注明原文地址:https://www.9cbs.com/read-125894.html

New Post(0)