Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Training - Day 2 The Web Agenda • • • • • • Introduction to Struts JSP – Java Server Pages The Struts Tag Libraries JSTL – JSP Standard Template Library Advanced Struts Features DisplayTag What is Struts? • Struts is an open source framework that provides a “Model 2” paradigm, a variation of MVC, for web programming. – Business logic execution – Presentation logic • Multiple frameworks – Struts Action Framework – Struts Shale Framework – Lots of extensions… How Does Struts Work? • Java Servlets are designed to handle requests made by Web browsers • Java Server Pages are designed to create dynamic Web pages that can turn normal web sites into live applications • Struts uses a special Servlet as a switchboard to route requests from Web browsers to the appropriate Server Page. • This makes Web applications much easier to design, create, and maintain. Continued • A web application has a deployment descriptor called web.xml • Describes the configuration of your web application – Welcome pages (the file that is shown in a directory when none is specified by the request), – Mappings to servlets (path or extension name), and parameters to those servlets. • Here is where you configure the Struts ActionServlet as the servlet that will handle all requests for a given mapping (usually the extension .do). Continued • In the Struts configuration file, you associate paths with the controller components of your application, known as Action classes – Login ==> LoginAction class – This tells the Struts ActionServlet that when the incoming request is http://myhost/myapp/Login.do it should invoke your controller component LoginAction • Note the extension .do in this URL. • The extension causes your container (Tomcat) to call the ActionServlet, which sees the word “Login" as the thing you want to do • The configuration is referenced, and your LoginAction is executed. Continued • For each Action, you also configure Struts with the names of the resulting page(s) that can be shown as a result of that action. • There can be more than one view as the result of an action – one for success – one for failure, etc • Your Action is based on these logical result mapping names • It reports back to the ActionServlet using words like "success", "failure", "ready", "ok", etc • The Struts system knows how to forward to the proper specific page • This has the added advantage of reconfiguration of the view layer by simply editing the Struts XML configuration file • At this point Struts knows how to delegate to your controller components, and what to show as a result of your controller processing • The "model" part of the application is completely up to you, and is called from within your controller components Continued • You may also associate a Java Bean with an action in the Struts configuration file • The Java Bean is used as a repository for form or display data that can be communicated between the view and controller layer • These Beans are automatically made visible to your controller components (like LoginAction) and any view page that is associated with that controller • You must be using some sort of server-side technology (JSP in our case) for the view layer to see this data (plain HTML won't work). • The client feeds the data back through normal form submission (POST/GET) methods, and Struts updates that data in the Bean before calling your controller components Notes to remember • It is important to remember that this Struts mechanism, or lifecycle, is only in effect when the ActionServlet is handling the request • Since this only happens when a request is submitted that causes your container to call ActionServlet, you must be sure that any page that relies on Struts is done through a request that will map to the ActionServlet. Looking at some of the pieces • Actions • Forms • Views MVC – The Controller • Acts as a bridge between an application’s model and views. • When an application receives a request, the controller invokes an Action. • Actions are controllers with a specific responsibility, and an application will be made up of multiple Actions. Action Example • Let’s take a look at the MovieAction.java file in the exercises project. MVC – The Model • ActionForms are the model in the Struts mindset. This is not your application’s model. • This is where data is passed from an Action to a view. • Basically, just a simple java bean. ActionForm Example • Let’s take a look at the MovieForm.java file in the exercises project. Web Domain Objects • Helper object that cleans up the code in ActionForms and on JSP pages - help to not lock you in to Struts – Not a part of Struts – Something we use on SIT team • A place for fields that might be needed on a web page, but should not be associated with a true domain object (gets saved to a database). • Provides a hook for web validation. • If you don’t have extra fields or need web validation, just use the real domain object. • Let’s take a look at the WebRental.java file in the exercises project. MVC – The View • We uses Java Server Pages (JSP) as the view technology, rather than JSF or VT, etc. • Use an ActionForm/Request to retrieve data. • Tag libraries can be used in conjunction with JSP - JSTL and DisplayTag are common examples. • Examples coming up in the JSP/JSTL sections. Exercise: Actions and Forms • There are TODO statements scattered throughout – MovieAction.java – MovieForm.java Wiring Application Logic • Configuration of application logic is done in the struts-config.xml file. • Allows declarative logic in XML rather than in the application code. • Allows re-configuration of application logic without recompilation. Example <?xml version="1.0" encoding="ISO-8859-1" ?> <!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN" "http://struts.apache.org/dtds/struts-config_1_2.dtd"> <struts-config> <form-beans> <form-bean name="logonForm" type="app.LogonForm"/> </form-beans> <action-mappings> <action path="/Welcome" forward="/pages/Welcome.jsp"/> <action path="/Logon" forward="/pages/Logon.jsp"/> <action path="/LogonSubmit" type="app.LogonAction" name="logonForm" scope="request" validate="true" input="/pages/Logon.jsp"> <forward name="success" path="/pages/Welcome.jsp"/> <forward name="failure" path="/pages/Logon.jsp"/> </action> <action path="/Logoff" type="app.LogoffAction"> <forward name="success" path="/pages/Logoff.jsp"/> </action> </action-mappings> <message-resources parameter="resources.application"/> </struts-config> Time to look at the trn configuration file • Let’s find the struts-config.xml file in the exercises project and look at it Exercise: Wire Struts • Time for you to go in and complete all of the TODO items in the struts-config.xml for the trn project. Application Resources (Messages) • Application Resources is a file that can contain all text messages that appear in an application. • Provides a single point for all textual messages: easy to keep consistent, change out side of the code, etc. • Makes it possible for i18n. Example application.title=My Application group.error=The group {0} is invalid error.username.missing=You must type in a username error.password.missing=You must type in a password username.message=Username: password.message=Password: submit.button.message=Save Let’s take a look at the ApplicationResources.properties file out in the trn project. Adding Struts to a Web App • Configuring Struts <servlet> <servlet-name>action</servlet-name> <servlet-class>org.apache.struts.action.ActionServlet</servlet-class> <init-param> <param-name>application</param-name> <param-value>edu.iu.uis.train.ApplicationResources</param-value> </init-param> <init-param> <param-name>config</param-name> <param-value>/WEB-INF/struts-config.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>action</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> • Configuring the taglibs for Struts <taglib> <taglib-uri>http://struts.apache.org/tags-html-el</taglib-uri> <taglib-location>/WEB-INF/struts-html-el.tld</taglib-location> </taglib> Java Server Pages • If you can write HTML pages, you are well on your way to writing JSP • Combination of: – HTML tags – Struts HTML-EL tags – JSTL tags • Let’s take a look at MovieDetail.jsp struts-html-el • Contain tags that – handle form HTML elements – handle re-writing HREF’s – display user interface errors – deal with a user’s locale <%@ taglib uri="http://struts.apache.org/tags-html-el" prefix="html-el" %> struts-html-el <html-el> • Looks at browser’s locale setting and enables i18n based on user’s locale. <html-el:html locale=“true”> struts-html-el <html-el:errors> • Displays a single error message or all error messages saved in the servlet context • Action object/Form object can add errors as necessary – We typically do this in a validation <html-el:errors/> <html-el:errors property=“projectName”/> struts-html-el <html-el:form> • Start an HTML form where all input is sent to a Form object • POSTS or GETS to an action in strutsconfig.xml <html-el:form action=“/Movie.do”> struts-html-el • Form Input tags – – – – – – – button cancel checkbox hidden multibox option options password radio reset select submit text textarea All of these are just like their HTML counterparts with a property attribute that work with a Form struts-html-el <html-el:link> • Create <a href> and handle url rewriting • Use to provide links to locations within your application <html-el:link href=“/Movie.do”> some link text or image </html-el:link> struts-html-el <html-el:image> Create an image for submitting Probably going to be the standard way to do buttons in the UIS look and feel Note the property – this is how Struts knows if you clicked the image <html-el:image src="images/buttonsmall_save.gif" property="methodToCall.saveBanUser2" /> JSTL • JSP Standard Tag Library • Set of tags that should be available in all compliant JSP containers • Promotes rapid application development at the web page layer Why do we need JSTL? • A big reason is that writing your own custom actions, or tags, can be a pain • There was lots of reinventing the wheel going on, for tasks like displaying a date in a special format • Many open source libraries sprung up, but there was still no standard • This fueled the fire behind JSTL What do you get? • Core – Variables, logic and control flow, output • XML – Importing and parsing xml documents, xpath • SQL – Datasources, queries, updates, transactions • i18n and Formatting – Data/time formatting and i18n messaging The Expression Language • Very important part of JSTL <c:if test="${book.orderQuantity > book.inStock}"> The book ${book.title} is currently out of stock. </c:if> • ${ … } are the expressions – – – – Access JavaBean properties using . (dot) ${book.title} translates to book.getTitle() Access to Array and Collection elements using collection[] Access to a Map value by key using map[“key”] • EL searches each scope area if a scope isn’t specified • Specific scope areas can be used: – – – – ${pageScope.title} ${requestScope.title} ${sessionScope.title} ${applicationScope.title} EL Operators • Arithmetic – +, -, *, / (or div), % (or mod) – note on XPath • Relational – == (or eq), != (or ne), < (or lt) – > (or gt), <= (or le), >= (or ge) • Logical – && (or and), || (or or), ! (or not) • Validation – empty • null values • Collections or Arrays that are empty • Strings that evaluate to “” Implicit objects available in EL • param and paramValues – access HTTP request parameters • header and headerValues – request header information • initParam (for the context init parameters of the webapp) • cookies Automatic Type Conversion • Authors do not have to worry about converting types • For example, a String parameter from a request will be coerced to the appropriate object or primitive Taglib Directives • Must be included on the page that you want to use the tags • Here is a directive for the core library <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> Variables • <c:set var="name" scope="scope" value="expression"/> – The scope attribute is optional and defaults to page • <c:set var="timezone" scope="session">CST</c:set> • <c:remove var="timezone" scope="session"/> Output • <c:out value="expression" default="expression" escapeXml="boolean"/> – Default printed if its value null or an empty String – escapeXml controls whether or not characters such as "<", ">", and "&" should be escaped • Shortcut – ${expression} can be used in some containers Flow Control • Iteration • Condition • Exception Handling Iteration • A loop with a start, end, and step (typical for statement) <c:forEach var="name" varStatus="name" begin="expression" end="expression" step="expression"> body content </c:forEach> • A loop using an Iterator for a collection <c:forEach var="name" items="expression" varStatus="name" begin="expression" end="expression" step="expression"> body content </c:forEach> Example <table> <tr><th>Value</th><th>Square</th></tr> <c:forEach var="x" begin="0" end="10" step="2"> <tr> <td>${x}</td> <td>${x * x}</td> </tr> </c:forEach> </table> Another Example <table> <c:forEach items="${entryList}" var="blogEntry"> <tr><td align="left" class="blogTitle"> ${blogEntry.title} </td></tr> <tr><td align="left" class="blogText"> ${blogEntry.text} </td></tr> </c:forEach> </table> Conditionals <c:if test="expression" var="name" scope="scope"> body content </c:if> <c:choose> <c:when test="expression"> body content </c:when> ... <c:otherwise> body content </c:otherwise> </c:choose> Example <c:choose> <c:when test="${pageContext.request.scheme eq 'http'}"> This is an insecure Web session. </c:when> <c:when test="${pageContext.request.scheme eq 'https'}"> This is a secure Web session. </c:when> <c:otherwise> You are using an unrecognized Web protocol. How did this happen?! </c:otherwise> </c:choose> Exception Handling • Rudimentary exception handling within a JSP page • Any exceptions raised within the body content of this tag will be caught and ignored, unless var is specified (exception stuck in var) for custom error handling <c:catch var="name"> body content </c:catch> Formatting <fmt:formatDate value="expression" timeZone="expression" type="field" dateStyle="style" timeStyle="style" pattern="expression" var="name" scope="scope"/> <fmt:setBundle basename="expression" var="name" scope="scope"/> <fmt:message key="expression" bundle="expression" var="name" scope="scope"/> Example <table> <fmt:timeZone value="US/Eastern"> <c:forEach items="${entryList}" var="blogEntry" varStatus="status"> <c:if test="${status.first}"> <tr> <td align="left" class="blogDate"> <fmt:formatDate value="${blogEntry.created}" dateStyle="full"/> </td> </tr> </c:if> <tr> <td align="left" class="blogTitle">${blogEntry.title}</td> </tr> <tr> <td align="left" class="blogText">${blogEntry.text} <font class="blogPosted"> [Posted <fmt:formatDate value="${blogEntry.created}" pattern="h:mm a zz"/>] </font> </td> </tr> </c:forEach> </fmt:timeZone> </table> Example Output The rest of JSTL • Check out the references for the rest of the JSTL libraries – The rest of FMT – SQL – XML • Also take a look at some of the JSP files in the exercises application for examples. Exercise: JSP and JSTL • Movie.jsp has numerous TODO items throughout. At this time, you should have enough information to fix this file. Advanced Struts Topics • Using the Struts Dispatch Action – A few examples • An Action with and without Dispatch • A struts-config.xml file with and without • MainAction.java in the trn project • Struts Request Processor – Configured via a controller <controller processorClass= "edu.iu.uis.train.application.TrainingStrutsRequestProcessor" /> • Message Resources – Support for i18n of your messages <message-resources parameter="edu.iu.uis.train.ApplicationResources" /> • Dynamic Forms (not something we use) http://struts.apache.org//struts-doc1.2.9/userGuide/building_controller.html#dyna_action_form_classes Other stuff… • UIS Dispatch Base Action – Method to call DisplayTag What can it do? • Actually the display tag library can just... display tables! • Give it a list of objects and it will handle – – – – – – – – Column display Sorting Paging Cropping Grouping Exporting Smart linking Decoration of a table in a customizable XHTML style Displaying a List of Objects <% request.setAttribute( "test", new TestList(10, false) ); %> <display:table name="test"> <display:column property="id" title="ID" /> <display:column property="name" /> <display:column property="email" /> <display:column property="status" /> <display:column property="description" title="Comments"/> </display:table> What get’s displayed in a column • A column will display whatever the property value tells it to display by calling the getter for that bean property Getting access in EL • If you assign an id attribute, you can use that in EL <display:table id="row" name="mylist"> <display:column title="row number" > ${row_rowNum} </display:column> <display:column title="name" > ${row.first_name} ${row.last_name} </display:column> </display:table> DisplayTag: Things to remember • We store the data in session for faster paging and sorting (listKey) • If you need multiple links, you may need to hardcode the entire url in the action property Looking at some code • Let’s take a look at MovieDetail.jsp in the exercises project for a real example Exercise: DisplayTag • In <webapp>/WEB-INF/jsp/movie finish the display tag in MovieList.jsp • There is a TODO that explains what needs to be done References • Struts Action Framework http://struts.apache.org/struts-action/ • Practical JSTL Part 1 http://today.java.net/pub/a/today/2003/10/07/jstl1.html • IBM JSTL Tutorial Part 1 http://www-128.ibm.com/developerworks/java/library/j-jstl0211.html • IBM JSTL Tutorial Part 2 http://www-128.ibm.com/developerworks/java/library/j-jstl0318/ • IBM JSTL Tutorial Part 3 http://www-128.ibm.com/developerworks/java/library/j-jstl0415/ • The Display Tag Library http://displaytag.sourceforge.net/10/