Uploaded on

Jakarta struts

Jakarta struts

More in: Education , Technology
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
    Be the first to like this
No Downloads

Views

Total Views
372
On Slideshare
0
From Embeds
0
Number of Embeds
0

Actions

Shares
Downloads
5
Comments
0
Likes
0

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide

Transcript

  • 1. CP237Java Programming II
  • 2. Jakarta Struts• Introduction• Struts Architecture• Installing Struts• Action Form• Action Servlet• struts_config.xml• Custom tags
  • 3. What is Struts?There are several different ways of looking at Struts. The three main ways arethat Struts is:An MVC Framework.Struts provides a unified framework for deploying servlet and JSP applicationsthat use the MVC architecture.A Collection of Utilities.Struts provides utility classes to handle many of the most common tasks in Webapplication developmentA Set of JSP Custom Tag Libraries.Struts provides custom tag libraries for outputting bean properties, generatingHTML forms, iterating over various types of data structures, and conditionallyoutputting HTML.
  • 4. Struts Framework
  • 5. 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 thestruts_install_dir.Update your CLASSPATH.Add struts_install_dir/lib/struts.jar to the CLASSPATH used by your compiler orIDE (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 intoC:jakarta-struts-1.1, you would add the following to C:autoexec.bat:set CLASSPATH=C:jakarta-strutslibstruts.jar;%CLASSPATH%On Unix/Linux, use your .cshrc, .bashrc, or .profile instead.
  • 6. Installing StrutsSet it using the system settings. On WinXP, go to the Start menu and selectControl Panel, then System, then the Advanced tab, then the EnvironmentVariables button. On Win2K/WinNT, go to the Start menu and select Settings,then Control Panel, then System, then Environment. Either way, enter theCLASSPATH value from the previous bullet.Set it in your editor or IDE. Most IDEs have a way of specifying the JAR filesneeded to compile projects. Or, you could make a small .bat file (Windows) orshell 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 theyalready come with an XML parser. But, if you use JDK 1.2 or 1.3 with anotherserver, you might need to obtain the XML parsing libraries. Here are two goodsources:http://xml.apache.org/http://java.sun.com/xml/
  • 7. 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
  • 8. Struts *.war filesFound in the following installation directory: struts-1.2.7webapps• struts-blank.war• struts-documentation.war• struts-examples.war• struts-mailreader.war• tiles-documentation.war
  • 9. Struts.jar• Be sure to place the struts.jar into your JS2E_HOMEjrelibext directory
  • 10. Testing StrutsInstall struts-blank.war.Install the Web application from struts_install_dir/webapps/struts-blank.war onyour 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 usingport 80. In general, access http://hostname:port/struts-blank/. You should seesomething like the following.
  • 11. Struts Install Successful
  • 12. Setting Up Struts ApplicationsTo make your own Struts application, you need to create a Web application thathas the appropriate JAR files, TLD files, and web.xml entries. You almostalways do this by starting with the struts-blank application and modifying it. Youhave three options for doing this:Option 1 (Good): Copy/rename the struts-blank directory to yourdevelopment 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.warfile into the struts-blank directory. So, copy that directory to whatever locationyou use for developing custom Web applications, and rename it to whatever appname you choose. For example, if you are using Tomcat and devel_dir is thelocation 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.
  • 13. Setting Up Struts ApplicationsOption 2 (Good): Unjar struts-blank.war into your development directory.If your server doesnt automatically unpack WAR files, then even if you ran thestruts-blank test described above, you have no regular directory to work with.Besides, some people prefer to unpack the WAR file themselves anyhow. Todo 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 servers Web application autodeploy directory (e.g., onto the shortcut to tomcat_install_dir/webapps).
  • 14. Setting Up Struts ApplicationsOption 3 (Bad): Rename struts-blank and leave it in the serversdeployment directory.It is quite common to work directly in servers deployment directory (e.g., towork directly in tomcat_install_dir/webapps/struts-test). However, thisapproach scales poorly to real applications, makes it harder to test changes(you have no stable working version), and doesnt support your "real"deployment server anyhow (which is almost certainly not your desktopmachine). If you dont have a good deployment system using your IDE or antscripts, you can easily make a shortcut (Windows) or symbolic link (Unix/Linux)to the servers autodeploy directory, and just copy the Web app onto theshortcut 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, asdescribed above.Deploy by using the right mouse to drag struts-test onto the shortcut from step1, releasing, and choosing "Copy".
  • 15. Adding Struts to an Existing Web ApplicationBy far the easiest way to develop a Struts application is to start with struts-blank, renameit, and work from there. if you already have an existing Web application and want to addStruts capabilities to it, starting with struts-blank wont work. Adding Struts capabilities toexisting Web apps is a huge pain in the neck, and will probably require several attemptsto 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 toyour_web_app/WEB-INF/classes/resources.If you plan on using the automatic validator (see Section 5, Validating User Input), copyvalidation.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 mapblah.do to org.apache.struts.action.ActionServlet. Be sure you keep the entries in thesame locations: the order of elements in web.xml matters.
  • 16. Accessing Struts DocumentationYou probably already have bookmarked the APIs for standard Java, servlets,and JSP. But you will also want to frequently refer to the Apache Strutsdocumentation. 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 localcopy, install the struts-documentation.war Web app. For example, if you areusing Apache Tomcat on port 80 on your local machine, copy struts_install_dir/webapps/struts-documentation.war to tomcat_install_dir/webapps, restartserver, 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 thedocumentation. 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.
  • 17. The Six Basic Steps in Using Jakarta StrutsWith Struts, the normal processing flow is that a form submits data to a URL ofthe form blah.do. That address is mapped by struts-config.xml to an Actionobject, whose execute method handles the request.One of the arguments to execute is a form bean that is automatically createdand whose properties are automatically populated with the incoming form data.The Action object then invokes business logic and data-access logic, placingthe results in normal beans stored in request, session, or application scope.The Action uses mapping.findForward to return a condition, and the conditionsare mapped by struts-config.xml to various JSP pages. The system forwardsthe request to the appropriate JSP page, where the bean:write tag is used tooutput properties of the form bean and results beans.Optionally, both the input form and the final JSP pages can use bean:messageto output standard messages and labels as defined in a system property file.
  • 18. The Six Basic Steps in Using Jakarta StrutsHere 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.
  • 19. The Six Basic Steps in Using Jakarta StrutsCreate results beans.In the MVC architecture, the business-logic and data-access code create theresults and the JSP pages present them. To transfer the results from one layer tothe other, they are stored in beans. These beans differ from form beans in thatthey need extend no particular class, and they represent the output of thecomputational process, not the input to the process. Beans will be discussed inthe next set of slidesCreate an Action object to handle requests.The struts-config.xml file designates the Action object that handles requests forvarious URLs. The Action objects themselves need to do the real work: invokethe appropriate business- and data-access-logic, store the results in beans, anddesignate 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.
  • 20. The Six Basic Steps in Using Jakarta StrutsCreate form that invokes blah.do.You need to create an input form whose ACTION corresponds to one of the *.do addresseslisted 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 tagto build this input form.Display results in JSP.Since Struts is built around the MVC architecture, these JSP pages should avoid JSPscripting elements whenever possible. For basic Struts, these JSP pages usually use theStruts bean:write tag, but in JSP 2.0 the JSP 2.0 expression language is a viablealternative. 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 theAction, since it is the Action that invokes the logic that creates the data that the JSP pageswill display. So, the JSP pages are placed in WEB-INF, where RequestDispatcher canforward to them but where clients cannot access them directly. If the JSP pages makessense independently of the Action (e.g., if they display session data), then the JSP pagesshould be placed in a regular subdirectory of the Web application, and the forward entriesin struts-config.xml should say <forward ... redirect="true"/>.
  • 21. Let’s do a simple example…In this example, the URL http://hostname/struts-test/actions/register1.doshould be handled by the class RegisterAction1 (which extends Actionclass). RegisterAction1 always returns "success", and this return valueresults in the JSP page /WEB-INF/results/result1.jsp being displayed tothe client.
  • 22. 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 thatRegisterAction1 should handle requests for /actions/register1.do (notice that .do is impliedautomatically). To accomplish this, we add an action entry to action-mappings, where action has thefollowing 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 thatresult1.jsp applies when RegisterAction1 returns "success", as follows:<forward name="success" path="/WEB-INF/results/result1.jsp"/>
  • 23. 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, wedesignate that RegisterAction1 should handle requests for /actions/register1.do(notice that .do is implied automatically). To accomplish this, we add an actionentry 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.
  • 24. Modify struts-config.xml
  • 25. Register exampleDefine 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.
  • 26. Create an Action object to handle requestsIn 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 otherwiseneeded. In this case, we haveimport javax.servlet.http.*;import org.apache.struts.action.*; (this is why you need to be sure that youhave the struts.jar file in your J2SEjrelibext directoryExtend the Action class. In this case, we havepublic class RegisterAction1 extends Action {...}
  • 27. Create an Action object to handle requestsOverride 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 returnvalues. These values will then be mapped to specific JSP pages by forward entriesin 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")); }
  • 28. RegisterAction1.java
  • 29. register1.jspCreate 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 anduse a relative URL for the ACTION as follows. register1.jsp (Excerpt)
  • 30. URL Design Strategy
  • 31. Display results in JSPIn general, there can be several possible JSP pages corresponding to thevarious 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 appropriateaction. 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 simplemessage, as shown below In general, there can be several possible JSP pagescorresponding to the various possible return values of the execute method of theAction. In struts-config.xml, each JSP page is declared in a forward entry withinthe 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 simplemessage, as shown on the next slide.
  • 32. result1.jsp
  • 33. Executing the Form
  • 34. Executing the FormThis form is then filled in and submitted, with the forms ACTION resulting in theURL http://localhost/struts-test/actions/register1.do. This address is mapped bystruts-config.xml to the RegisterAction1 class, whose execute method isinvoked. 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 isinvoked with RequestDispatcher.forward, not response.sendRedirect, the URLdisplayed to the user is register1.do, not result1.jsp. See the following screenshot.
  • 35. Final Result