Baixe 04 - Struts - Forms e outras Notas de estudo em PDF para Cultura, somente na Docsity!
Slides © Marty Hall, http://www.coreservlets.com, books © Sun Microsystems Press
Jakarta Struts:
Prepopulating and
Redisplaying Input Forms
Struts 1.2 Version
Core Servlets & JSP book: www.coreservlets.com More Servlets & JSP book: www.moreservlets.com Servlet/JSP/Struts/JSF Training: courses.coreservlets.com
Slides © Marty Hall, http://www.coreservlets.com, books © Sun Microsystems Press
For live Struts training, please see
JSP/servlet/Struts/JSF training courses at
http://courses.coreservlets.com/.
Taught by the author of Core Servlets and JSP , More
Servlets and JSP , and this tutorial. Available at public
venues, or customized versions can be held on-site at
your organization.
5 Apache Struts: Handling Forms www.coreservlets.com
Agenda
- Using the Struts html: tags to build HTML forms that have three important characteristics: - The textfield names and the bean properties are
guaranteed to stay in synch
- The textfield values can be prepopulated based on the
values in a bean.
- That is, the initial values of the form elements can be taken from a Java object.
- The forms can be redisplayed when they are submitted
with incomplete or incorrect values.
- Specifically, when they are redisplayed, they can maintain the values that the end user already entered.
Struts Flow of Control
JSP
Form
Determine Action
Action
Choose JSP Page
JSP
request .../SomeForm.jsp submit form request .../ blah .do
invoke execute method
return condition
return final result forward to
struts-config.xml Populate bean and pass to execute method.
Use bean:write.
Use html:form to build form.
9 Apache Struts: Handling Forms www.coreservlets.com
The Six Basic Steps in Using
Struts: Updates
3. Create results beans. - These are normal beans of the sort used in MVC when
implemented directly with RequestDispatcher, and are
created and used in the same way as described in the
previous section.
4. Define an Action class to handle requests. - As in the previous section, rather than calling
request.getParameter explicitly, the execute method
casts the ActionForm argument to the specific form
bean class, then uses getter methods to access the
properties of the object.
The Six Basic Steps in Using
Struts: Updates
5. Create form that invokes blah.do.
- Rather than using the standard HTML FORM and INPUT tags, we now use html:form and html:text (and related tags).
- The html:form tag associates a bean with the form, and html:text automatically uses bean property names for each textfield NAME and bean property values for each textfield VALUE.
- In addition, as in the previous section, this form can still use the bean:message tag to output standard messages and text labels.
6. Display results in JSP.
- As before, the JSP page uses bean:write to output properties of the form and result beans.
- It may also use bean:message to output standard messages and text labels that are defined in a properties file.
11 Apache Struts: Handling Forms www.coreservlets.com
New Techniques
- Using html:form to declare form in initial JSP page.
- The action should exactly match path attribute of action element in struts-config.xml
- Using the Struts html:form element instead of the
standard HTML FORM element yields four results:
- A bean is associated with the form.
- A bean of the type specified by form-bean is automatically used
- The Web application prefix is prepended automatically.
- You say <html:form action="/actions/..."> to get <FORM ACTION=" /webAppPrefix /actions/..." ...>.
- The .do suffix is appended automatically.
- You say <html:form action="/actions/blah"> to get <FORM ACTION="/webAppPrefix/actions/blah .do " ...>.
- POST, not GET, is the default METHOD.
- You say <html:form action="/actions/blah"> to get <FORM ACTION="/webAppPrefix/actions/blah.do" METHOD="POST" >.
New Techniques
- Using html:text and similar elements to declare the
input fields of the form.
- The NAME of each input field is taken from the bean property name, and the VALUE is taken from the bean property value. For example, using <html:text property="firstName"/> is equivalent to first declaring a bean of the appropriate type, then doing <INPUT TYPE="TEXT" NAME="firstName" VALUE="<%= theBean.getFirstName() %>">.
- Not only does this provide initial values for your form fields, but it also makes it easier for you to be sure that the field names match the bean property names. Since, in the execute method of the Action object, the form bean is filled in by matching up request parameter names with bean property names, it is critical that the names stay in synch.
15 Apache Struts: Handling Forms www.coreservlets.com
Example 1: Signing up for
Alerts/Notifications
- URL
- http:// hostname /signup/actions/signup1.do
- Action Class
- SignupAction
- Uses a ContactFormBean that is automatically filled in
- The execute method returns "success" or "missing-value"
- Results pages
confirmation.jsp
missing-value.jsp
Step 1 (Modify struts-config.xml)
- Map incoming .do address to Action classes
- As before, we use the action element (to designate that SignupAction1 should handle requests for signup1.do).
- Map return conditions to JSP pages
- As before, we use multiple forward elements, one for each possible return value of the execute method
- However, since two different Actions will eventually use the same condition to indicate the same JSP page, the repeated mapping will go in global-forwards. <global-forwards> </global-forwards>
- Declare any form beans that are being used.
- As before, we use name and type attributes within form-bean
- As before, we also add name (the bean name as given in form-bean) and scope (request) attributes to the action declaration.
17 Apache Struts: Handling Forms www.coreservlets.com
Step 1 (Modify struts-config.xml) –
Final Code
<struts-config> <form-beans> <form-bean name="contactFormBean" type="coreservlets.ContactFormBean"/> </form-beans> <global-forwards> </global-forwards> <action-mappings> ... </action-mappings> </struts-config>
Step 2 (Define a Form Bean)
- Same behavior in the Action
- The form bean extends ActionForm, is automatically
filled in with the incoming form parameters, and is passed
to the execute method of the Action
- Also used in the form
- In addition to being used in the Action, the html:form tag
indicates that a new instance of the form bean will be
created and used to fill in the fields of the input form
- The NAME of the input field comes from the bean property name and the VALUE comes from the bean property value.
- For example, the following slide shows a form bean corresponding to contact information for a person that will be added to an email/fax list in our application. It contains properties for first name, last name, email address, etc.
21 Apache Struts: Handling Forms www.coreservlets.com
Step 3 (Create Results Beans)
- The form bean represents the input data
- I.e., the data that came from the HTML form.
- The results beans represent the output data
- I.e., the data created by the business logic to represent the
results of the computation or database lookup.
- The next slide shows a bean (MessageBean) that will be used to store simple error messages.
Step 3 (Create Results Beans) –
Code for MessageBean
package coreservlets;
public class MessageBean { private String message = "";
public String getMessage() { return(message); }
public void setMessage(String message) { this.message = message; } }
23 Apache Struts: Handling Forms www.coreservlets.com
Step 4 (Define an Action Class to
Handle Requests)
- In this example, we check each of the required input
parameters (first name, last name, email address, and
fax number) to see if it is missing.
- If it is missing, we use mapping.findForward to return a "missing- value" condition, which is mapped by struts-config.xml to an error page that contains a message saying which parameter was missing.
- If all parameters are present, we return "success", which results in an order-confirmation page.
- This example is similar to the previous one.
- Again, we do not call request.getParameter explicitly, but instead extract the request parameters from the already populated form bean. Specifically, we take the ActionForm argument supplied to execute, cast it to ContactFormBean (our concrete class that extends ActionForm), and then call getter methods on that bean.
- Also, we pass the error message to the JSP page by creating a MessageBean and storing it in request scope.
- It is also common to store results beans in a field of the form bean
Step 4 (Define an Action Class to
Handle Requests) -- Code
public class SignupAction1 extends Action { public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ContactFormBean userBean = (ContactFormBean)form; String firstName = userBean.getFirstName(); String lastName = userBean.getLastName(); String email = userBean.getEmail(); String faxNumber = userBean.getFaxNumber(); if (userBean.isMissing(firstName)) { makeWarning(request, "first name"); return(mapping.findForward("missing-value")); } ... } else { return(mapping.findForward("success")); } }
27 Apache Struts: Handling Forms www.coreservlets.com
Step 5 (Create Form that Invokes
blah .do), Continued
- Bean corresponding to the action is used
- Since the action of html:form matches the path attribute
of the action declaration in struts-config.xml, a bean is
automatically created when the input page is accessed.
- The type of bean created is determined by looking at the name that goes with the action, and finding the form-bean with the same name.
- In this case, the bean used is a ContactFormBean
- Bean names/properties are used for form fields
- After declaring the form and associating it with a bean,
we use html:text to build input elements whose NAME
and VALUE are taken from the form bean property
names and values.
Step 5 (Create Form that Invokes
blah .do), html:text Details
First name: <html:text property="firstName"/>
results in something similar to:
<jsp:useBean id="contactBean" scope="request"
class="coreservlets.ContactFormBean"/>
First name:
<INPUT TYPE="TEXT" NAME="firstName"
VALUE="${contactBean.firstName}">
- (And even worse if JSP 2.0 were not available)
29 Apache Struts: Handling Forms www.coreservlets.com
Step 5 (Create Form that Invokes
blah .do) – Final Code
**… the Single Provider of Alert Memos system lets you sign up for them all in one easy request!
<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html" %> First name:
Last name:
Email address:
Fax number: