Jakarta struts

35
CP237 Java Programming II

description

Jakarta struts

Transcript of Jakarta struts

Page 1: Jakarta struts

CP237Java Programming II

Page 2: Jakarta struts

Jakarta Struts

• Introduction• Struts Architecture• Installing Struts• Action Form• Action Servlet• struts_config.xml• Custom tags

Page 3: Jakarta struts

What is Struts?

There are several different ways of looking at Struts. The three main ways are that Struts is:

An MVC Framework.Struts provides a unified framework for deploying servlet and JSP applications that use the MVC architecture.

A Collection of Utilities.Struts provides utility classes to handle many of the most common tasks in Web application development

A Set of JSP Custom Tag Libraries.Struts provides custom tag libraries for outputting bean properties, generating HTML forms, iterating over various types of data structures, and conditionally outputting HTML.

Page 4: Jakarta struts

Struts Framework

Page 5: Jakarta struts

Installing StrutsDownload the Struts zip file.Start at http://jakarta.apache.org/site/binindex.cgi, or follow the link from http://jakarta.apache.org/struts/.

Unzip into a directory of your choice.For example, unzip into C:\jakarta-struts. This is refered to as the struts_install_dir.

Update your CLASSPATH.Add struts_install_dir/lib/struts.jar to the CLASSPATH used by your compiler or IDE (not your server). Here are three possible ways of setting it:

Set it in your autoexec.bat file. E.g., on Windows if you unzipped into C:\jakarta-struts-1.1, you would add the following to C:\autoexec.bat:

set CLASSPATH=C:\jakarta-struts\lib\struts.jar;%CLASSPATH%On Unix/Linux, use your .cshrc, .bashrc, or .profile instead.

Page 6: Jakarta struts

Installing Struts

Set it using the system settings. On WinXP, go to the Start menu and select Control Panel, then System, then the Advanced tab, then the Environment Variables button. On Win2K/WinNT, go to the Start menu and select Settings, then Control Panel, then System, then Environment. Either way, enter the CLASSPATH value from the previous bullet.

Set it in your editor or IDE. Most IDEs have a way of specifying the JAR files needed to compile projects. Or, you could make a small .bat file (Windows) or shell script (Unix/Linux) that supplies the struts.jar file as the argument to -classpath for javac.

Install an XML parser.If you have JDK 1.4 or Apache Tomcat, this step is not necessary, since they already come with an XML parser. But, if you use JDK 1.2 or 1.3 with another server, you might need to obtain the XML parsing libraries. Here are two good sources: http://xml.apache.org/ http://java.sun.com/xml/

Page 7: Jakarta struts

Installing Struts

• Download from jakarta web site• Get the appropriate operating system

download• Uncompress the downloaded file• Copy all of the *.war files from the

downloaded directory to your Tomcat webapps directory

• Start tomcat• Enter: http://localhost:8080/struts_blank

Page 8: Jakarta struts

Struts *.war files

• struts-blank.war

• struts-documentation.war

• struts-examples.war

• struts-mailreader.war

• tiles-documentation.war

Found in the following installation directory:

struts-1.2.7\webapps

Page 9: Jakarta struts

Struts.jar

• Be sure to place the struts.jar into your JS2E_HOME\jre\lib\ext directory

Page 10: Jakarta struts

Testing Struts

Install struts-blank.war.Install the Web application from struts_install_dir/webapps/struts-blank.war on your server. For example, with Apache Tomcat, copy struts_install_dir/webapps/struts-blank.war to tomcat_install_dir/webapps/.

Start or restart the server.Most servers only recognize new Web apps when the server is started.

Access http://localhost/struts-blank/.This URL assumes you are running the server on your desktop and are using port 80. In general, access http://hostname:port/struts-blank/. You should see something like the following.

Page 11: Jakarta struts

Struts Install Successful

Page 12: Jakarta struts

Setting Up Struts Applications

To make your own Struts application, you need to create a Web application that has the appropriate JAR files, TLD files, and web.xml entries. You almost always do this by starting with the struts-blank application and modifying it. You have three options for doing this:

Option 1 (Good): Copy/rename the struts-blank directory to your development directory.When you tested your Struts installation, you ran the struts-blank Web app. When you did so, Tomcat and most other servers unpacked the struts-blank.war file into the struts-blank directory. So, copy that directory to whatever location you use for developing custom Web applications, and rename it to whatever app name you choose. For example, if you are using Tomcat and devel_dir is the location you use for development, copy the tomcat_install_dir/webapps/struts-blank directory to devel_dir, rename it to struts-test, resulting in devel_dir/struts-test.

Page 13: Jakarta struts

Setting Up Struts Applications

Option 2 (Good): Unjar struts-blank.war into your development directory.If your server doesn't automatically unpack WAR files, then even if you ran the struts-blank test described above, you have no regular directory to work with. Besides, some people prefer to unpack the WAR file themselves anyhow. To do so:

Copy struts_install_dir/webapps/struts-blank.war to your development directory. Make a new directory (e.g., called struts-test). Unjar struts-blank.war into that directory You can use jar -xvf or a standard zip tool like WinZip or the Windows XP explorer. Whenever you want to test your application, copy struts-test to the server's Web application autodeploy directory (e.g., onto the shortcut to tomcat_install_dir/webapps).

Page 14: Jakarta struts

Setting Up Struts ApplicationsOption 3 (Bad): Rename struts-blank and leave it in the server's deployment directory.It is quite common to work directly in server's deployment directory (e.g., to work directly in tomcat_install_dir/webapps/struts-test). However, this approach scales poorly to real applications, makes it harder to test changes (you have no stable working version), and doesn't support your "real" deployment server anyhow (which is almost certainly not your desktop machine). If you don't have a good deployment system using your IDE or ant scripts, you can easily make a shortcut (Windows) or symbolic link (Unix/Linux) to the server's autodeploy directory, and just copy the Web app onto the shortcut each time. For example, suppose you are using Tomcat on Windows. To easily develop in one directory and then deploy in another, just do this: Grab tomcat_install_dir/webapps with your right mouse, drag it into devel_dir, release, and choose "Create Shortcut Here". Create struts-test or other applications as subdirectories within devel_dir, as described above. Deploy by using the right mouse to drag struts-test onto the shortcut from step 1, releasing, and choosing "Copy".

Page 15: Jakarta struts

Adding Struts to an Existing Web Application

By far the easiest way to develop a Struts application is to start with struts-blank, rename it, and work from there. if you already have an existing Web application and want to add Struts capabilities to it, starting with struts-blank won't work. Adding Struts capabilities to existing Web apps is a huge pain in the neck, and will probably require several attempts to get it right. Here is a quick summary: Copy JAR files from struts-blank/WEB-INF/lib to your_web_app/WEB-INF/lib. Copy TLD files from struts-blank/WEB-INF to your_web_app/WEB-INF. Copy struts-config.xml from struts-blank/WEB-INF to your_web_app/WEB-INF. Copy the application properties file from struts-blank/WEB-INF/classes/resources to your_web_app/WEB-INF/classes/resources. If you plan on using the automatic validator (see Section 5, Validating User Input), copy validation.xml and validator-rules.xml from struts-blank/WEB-INF to your_web_app/WEB-INF. If you plan on using Tiles (see Section 6, Composing Pages with Tiles), copy struts-tiles.xml from struts-blank/WEB-INF to your_web_app/WEB-INF. Copy declarations out of struts-blank/WEB-INF/web.xml into your_web_app/WEB-INF/web.xml. Most importantly, copy the servlet and servlet-mapping entries that map blah.do to org.apache.struts.action.ActionServlet. Be sure you keep the entries in the same locations: the order of elements in web.xml matters.

Page 16: Jakarta struts

Accessing Struts Documentation You probably already have bookmarked the APIs for standard Java, servlets, and JSP. But you will also want to frequently refer to the Apache Struts documentation. You can do this two ways:

Read a local copy.This is fastest, but the documentation can get a bit out of date. To read a local copy, install the struts-documentation.war Web app. For example, if you are using Apache Tomcat on port 80 on your local machine, copy struts_install_dir/webapps/struts-documentation.war to tomcat_install_dir/webapps, restart server, and use the URL http://localhost/struts-documentation/. Read it from the Apache site.

This option is slower, but guarantees that you get the latest versions of the documentation. To read the online version of the documentation, start at http://jakarta.apache.org/struts/learning.html. The documentation includes FAQs, user guides, tutorials, and the API in Javadoc format.

Page 17: Jakarta struts

The Six Basic Steps in Using Jakarta Struts

With Struts, the normal processing flow is that a form submits data to a URL of the form blah.do. That address is mapped by struts-config.xml to an Action object, whose execute method handles the request.

One of the arguments to execute is a form bean that is automatically created and whose properties are automatically populated with the incoming form data.

The Action object then invokes business logic and data-access logic, placing the results in normal beans stored in request, session, or application scope.

The Action uses mapping.findForward to return a condition, and the conditions are mapped by struts-config.xml to various JSP pages. The system forwards the request to the appropriate JSP page, where the bean:write tag is used to output properties of the form bean and results beans.

Optionally, both the input form and the final JSP pages can use bean:message to output standard messages and labels as defined in a system property file.

Page 18: Jakarta struts

The Six Basic Steps in Using Jakarta Struts

Here are the minimum steps needed to create an application that follows this process. This set of slides will focus on the basic flow and the Action objects; the next set of slides will show how to use beans.

Modify struts-config.xml.Use WEB-INF/struts-config.xml to: Designate Action classes to handle requests for blah.do. Specify the URLs that apply in various situations. Declare any form beans that are being used.

Be sure to restart the server after modifying struts-config.xml; the file is read only when the Web application is first loaded.

Define a form bean.This bean is a class the extends ActionForm and will represent the data submitted by the user. It is automatically populated when the input form is submitted. Beans will be discussed in the next set of slides.

Page 19: Jakarta struts

The Six Basic Steps in Using Jakarta Struts

Create results beans.In the MVC architecture, the business-logic and data-access code create the results and the JSP pages present them. To transfer the results from one layer to the other, they are stored in beans. These beans differ from form beans in that they need extend no particular class, and they represent the output of the computational process, not the input to the process. Beans will be discussed in the next set of slides

Create an Action object to handle requests.The struts-config.xml file designates the Action object that handles requests for various URLs. The Action objects themselves need to do the real work: invoke the appropriate business- and data-access-logic, store the results in beans, and designate the type of situation (missing data, database error, success category

1, success category

2, etc.) that is appropriate for the results. The struts-config.xml file then decides which JSP page should apply to that situation.

Page 20: Jakarta struts

The Six Basic Steps in Using Jakarta Struts

Create form that invokes blah.do.You need to create an input form whose ACTION corresponds to one of the *.do addresses listed in struts-config.xml. At a minimum, the input form should look like this:    <FORM ACTION=".../blah.do" ...>...</FORM>However, in future slides we will discuss the advantages of using the Struts html:form tag to build this input form.

Display results in JSP.Since Struts is built around the MVC architecture, these JSP pages should avoid JSP scripting elements whenever possible. For basic Struts, these JSP pages usually use the Struts bean:write tag, but in JSP 2.0 the JSP 2.0 expression language is a viable alternative. In complex cases, the JSP pages also use the JSP Standard Tag Library (JSTL) or the Struts looping/logic tags.

In most cases, the JSP pages only make sense when the request is funneled through the Action, since it is the Action that invokes the logic that creates the data that the JSP pages will display. So, the JSP pages are placed in WEB-INF, where RequestDispatcher can forward to them but where clients cannot access them directly. If the JSP pages makes sense independently of the Action (e.g., if they display session data), then the JSP pages should be placed in a regular subdirectory of the Web application, and the forward entries in struts-config.xml should say <forward ... redirect="true"/>.

Page 21: Jakarta struts

Let’s do a simple example…In this example, the URL http://hostname/struts-test/actions/register1.do should be handled by the class RegisterAction1 (which extends Action class). RegisterAction1 always returns "success", and this return value results in the JSP page /WEB-INF/results/result1.jsp being displayed to the client.

Page 22: Jakarta struts

Registration ExampleModify struts-config.xml.Use WEB-INF/struts-config.xml to: Designate Action classes to handle requests for blah.do. In this case, we designate that RegisterAction1 should handle requests for /actions/register1.do (notice that .do is implied automatically). To accomplish this, we add an action entry to action-mappings, where action has the following attributes.

path: the relative path that should be mapped to the Action, minus the .do extension. Thus, path="/actions/register1" refers to http://hostname/webAppName/actions/register1.do. See this section for a discussion of why it is useful to use /actions/register1 instead of just register1 in the path.

type: the fully qualified class name of the Action object that should be invoked when a request for the specified path is received.

name, scope, and input: these attributes are omitted in this example, but are used in later examples when beans are used.

In this case, the action element looks like this:<action path="/actions/register1"        type="coreservlets.RegisterAction1">  ...</action> Specify the URLs that apply in various situations. In this case, we use the forward element to say that result1.jsp applies when RegisterAction1 returns "success", as follows:<forward name="success"         path="/WEB-INF/results/result1.jsp"/> Declare any form beans that are being used. Beans are postponed until the next section, so this step is omitted for now.

Page 23: Jakarta struts

Modify struts-config.xmlModify struts-config.xml.Use WEB-INF/struts-config.xml to: Designate Action classes to handle requests for blah.do. In this case, we designate that RegisterAction1 should handle requests for /actions/register1.do (notice that .do is implied automatically). To accomplish this, we add an action entry to action-mappings, where action has the following attributes.

path: the relative path that should be mapped to the Action, minus the .do extension. Thus, path="/actions/register1" refers to http://hostname/webAppName/actions/register1.do. See this section for a discussion of why it is useful to use /actions/register1 instead of just register1 in the path.

type: the fully qualified class name of the Action object that should be invoked when a request for the specified path is received.

name, scope, and input: these attributes are omitted in this example, but are used in later examples when beans are used.

Page 24: Jakarta struts

Modify struts-config.xml

Page 25: Jakarta struts

Register example

Define a form bean.Beans are postponed, so this step is omitted for now.

Create results beans.Beans are postponed, so this step is omitted for now.

Page 26: Jakarta struts

Create an Action object to handle requests

In general, your Action subclass should:

Use a package. In this case, we havepackage coreservlets;This means that the class file should go in your_web_app/WEB-INF/classes/coreservlets/.

Add Struts-specific import statements to whatever imports are otherwise needed. In this case, we haveimport javax.servlet.http.*; import org.apache.struts.action.*; (this is why you need to be sure that you have the struts.jar file in your J2SE\jre\lib\ext directory

Extend the Action class. In this case, we have public class RegisterAction1 extends Action {...}

Page 27: Jakarta struts

Create an Action object to handle requests

Override the execute method. This method is defined as follows. public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ... }

Return mapping.findForward. The execute method should have one or more return values. These values will then be mapped to specific JSP pages by forward entries in struts-config.xml. In this case, we simply return "success" in all situations. public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { return(mapping.findForward("success")); }

Page 28: Jakarta struts

RegisterAction1.java

Page 29: Jakarta struts

register1.jsp

Create form that invokes blah.do.

In this case, we need an HTML form that invokes http://hostname/struts-test/actions/register1.do. We place the HTML form in the forms subdirectory and use a relative URL for the ACTION as follows.

register1.jsp (Excerpt)

Page 30: Jakarta struts

URL Design Strategy

Page 31: Jakarta struts

Display results in JSP

In general, there can be several possible JSP pages corresponding to the various possible return values of the execute method of the Action. In struts-config.xml, each JSP page is declared in a forward entry within the appropriate action. In this simple case, the only return value is "success", so /WEB-INF/results/result1.jsp is used in all cases. This JSP page displays a simple message, as shown below In general, there can be several possible JSP pages corresponding to the various possible return values of the execute method of the Action. In struts-config.xml, each JSP page is declared in a forward entry within the appropriate action. In this simple case, the only return value is "success", so /WEB-INF/results/result1.jsp is used in all cases. This JSP page displays a simple message, as shown on the next slide.

Page 32: Jakarta struts

result1.jsp

Page 33: Jakarta struts

Executing the Form

Page 34: Jakarta struts

Executing the Form

This form is then filled in and submitted, with the form's ACTION resulting in the URL http://localhost/struts-test/actions/register1.do. This address is mapped by struts-config.xml to the RegisterAction1 class, whose execute method is invoked. This method returns a mapping.findForward with a value of "success", and that value is mapped by struts-config.xml to /WEB-INF/results/result1.jsp, which is the final result displayed to the user. However, since the JSP page is invoked with RequestDispatcher.forward, not response.sendRedirect, the URL displayed to the user is register1.do, not result1.jsp. See the following screen shot.

Page 35: Jakarta struts

Final Result