Docsity
Docsity

Prepare-se para as provas
Prepare-se para as provas

Estude fácil! Tem muito documento disponível na Docsity


Ganhe pontos para baixar
Ganhe pontos para baixar

Ganhe pontos ajudando outros esrudantes ou compre um plano Premium


Guias e Dicas
Guias e Dicas


Introdução à Framework Struts utilizando JSP e Servlets, Notas de estudo de Cultura

Este documento fornece uma visão geral da framework struts versão 1.2, abordando conceitos como form e results beans, o uso da biblioteca de tags struts e a criação de beans para representar dados de entrada e resultados. Além disso, são apresentados exemplos de código em jsp e servlets.

Tipologia: Notas de estudo

Antes de 2010

Compartilhado em 31/08/2008

eric-mauricio-carvalho-4
eric-mauricio-carvalho-4 🇧🇷

5 documentos

1 / 18

Toggle sidebar

Esta página não é visível na pré-visualização

Não perca as partes importantes!

bg1
Slides © Marty Hall, http://www.coreservlets.com, books © Sun Microsystems Press
Jakarta Struts: Handling
Request Parameters with
Form Beans
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.
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12

Pré-visualização parcial do texto

Baixe Introdução à Framework Struts utilizando JSP e Servlets 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: Handling

Request Parameters with

Form Beans

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:Beans www.coreservlets.com

Agenda

  • Two new ideas
    • Automatically creating bean to represent request data
    • Using bean:write to output bean properties
  • Defining form beans
  • Declaring form beans
  • Outputting properties of form beans
    • bean:write
    • JSP 2.0 expression language
  • Defining and outputting regular beans

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 based on request parameters. Supply as second argument to execute.

Use bean:write to output bean properties.

9 Apache Struts:Beans www.coreservlets.com

The Six Basic Steps in Using

Struts: Updates for Bean Use

1. Modify struts-config.xml. Use WEB-INF/struts-config.xml to:

  • Map incoming .do addresses to Action classes
  • Map return conditions to JSP pages
  • Declare any form beans that are being used.
  • Restart server after modifying struts-config.xml. 2. Define a form bean.
    • This bean extends ActionForm and represents the data
submitted by the user. It is automatically populated
when the input form is submitted. More precisely:
1. The reset method is called (useful for session-scoped beans)
2. For each incoming request parameter, the corresponding setter
method is called
3. The validate method is called (possibly preventing the Action)

The Six Basic Steps in Using

Struts: Updates for Bean Use

3. Create results beans. - These are normal beans of the sort used in MVC when

implemented directly with RequestDispatcher. That is,
they represent the results of the business logic and data
access code. These beans are stored in request, session,
or application scope with the setAttribute method of
HttpServletRequest, HttpSession, or ServletContext,
just as in normal non-Struts applications.

4. Define an Action class to handle requests. - Rather than calling request.getParameter explicitly as in

the previous example, the execute method casts the
ActionForm argument to the specific form bean class,
then uses getter methods to access the properties of the
object.

11 Apache Struts:Beans www.coreservlets.com

The Six Basic Steps in Using

Struts: Updates for Bean Use

5. Create form that invokes blah .do. - For now, we will use static HTML - Later, we will use the html:form tag to guarantee that the

textfield names correspond to the bean property names, and to
make it easy to fill in the form based on values in the app
  • Later, we will also use bean:message to output fixed strings
from a properties file

6. Display results in JSP. - The JSP page uses the bean:write tag to output

properties of the form and result beans.
  • It may also use the bean:message tag to output standard
messages and text labels that are defined in a properties
file (resource bundle).

Example 1:

Form and Results Beans

  • URL
    • http:// hostname /struts-beans/register1.do
  • Action Class
    • BeanRegisterAction
      • Instead of reading form data explicitly with
request.getParameter, the execute method uses a bean that is
automatically filled in from the request data.
  • As in the previous example, this method returns "success",
"bad-address", or "bad-password"
  • Results pages
    • /WEB-INF/results/confirm-registration1.jsp
    • /WEB-INF/results/bad-address1.jsp
    • /WEB-INF/results/bad-password1.jsp

15 Apache Struts:Beans www.coreservlets.com

Step 1 (Modify struts-

config.xml), Continued

  • Update action declaration
    • After declaring the bean in the form-beans section, you
need to add two new attributes to the action element:
name and scope
  • name : a bean name matching the form-bean declaration.
  • scope : request or session. Surprisingly, session is the default, but
always explicitly list the scope anyhow. We want request here.
  • Here is an example.

Step 1 (Modify struts-

config.xml) -- Final Code

**

**

17 Apache Struts:Beans www.coreservlets.com

Step 2 (Define a Form Bean)

  • A form bean is a Java object that will be automatically filled in based on the incoming form parameters, then passed to the execute method. Requirements: - It must extend ActionForm. - The argument to execute is of type ActionForm. Cast the value to your real type, and then each bean property has the value of the request parameter with the matching name. - It must have a zero argument constructor. - The system will automatically call this default constructor. - It must have settable bean properties that correspond to the
request parameter names.
  • That is, it must have a set Blah method corresponding to each incoming request parameter named blah. The properties should be of type String (i.e., each set Blah method should take a String as an argument).
  • It must have gettable bean properties for each property that you
want to output in the JSP page.
  • That is, it must have a get Blah method corresponding to each bean property that you want to display in JSP without using Java syntax.

18 Apache Struts:Beans www.coreservlets.com

Step 2 (Define a Form Bean) --

Code Example

package coreservlets; import org.apache.struts.action.;*

public class UserFormBean extends ActionForm { private String email = "Missing address"; private String password = "Missing password";

public String getEmail() { return(email); }

public void setEmail(String email) { this.email = email; }

public String getPassword() { return(password); }

public void setPassword(String password) { this.password = password; } }

21 Apache Struts:Beans www.coreservlets.com

Step 3, Business Logic Code

(To Build SuggestionBean)

package coreservlets;

public class SuggestionUtils { private static String[] suggestedAddresses = { "[email protected]", "[email protected]", "[email protected]", "[email protected]" }; private static String chars = "abcdefghijklmnopqrstuvwxyz0123456789#@$%^&?!";*

public static SuggestionBean getSuggestionBean() { String address = randomString(suggestedAddresses); String password = randomString(chars, 8); return(new SuggestionBean(address, password)); } … }

Step 4 (Define an Action Class

to Handle Requests)

  • This example is similar to the previous one except that we do do not call request.getParameter explicitly. - Instead, we extract the request parameters from the
already populated form bean.
  • Specifically, we take the ActionForm argument supplied to
execute, cast it to UserFormBean (our concrete class that
extends ActionForm), and then call getter methods on that bean.
  • Also, we create a SuggestionBean and store it in request
scope for later display in JSP.
  • This bean is the result of our business logic, and does not
correspond to the incoming request parameters

23 Apache Struts:Beans www.coreservlets.com

Step 4 (Define an Action Class

to Handle Requests) -- Code

public ActionForward execute(ActionMapping mapping, ActionForm form, ... request, ... response) throws Exception { UserFormBean userBean = (UserFormBean)form; String email = userBean.getEmail(); String password = userBean.getPassword(); if ((email == null) || (email.trim().length() < 3) || (email.indexOf("@") == -1)) { request.setAttribute("suggestionBean", SuggestionUtils.getSuggestionBean()); return(mapping.findForward("bad-address")); } else if ((password == null) || (password.trim().length() < 6)) { request.setAttribute("suggestionBean", SuggestionUtils.getSuggestionBean()); return(mapping.findForward("bad-password")); } else { return(mapping.findForward("success")); } }

Step 5 (Create Form that

Invokes blah .do)

**

New Account Registration

New Account Registration

Email address: Password:

**

27 Apache Struts:Beans www.coreservlets.com

Step 6 (Display Results in JSP)

First Possible Page

**

Illegal Email Address

Illegal Email Address <%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %> The address "" is not of the form username@hostname (e.g., ).

Please try again.

**

Step 6 (Display Results in JSP)

Second Possible Page

**

Illegal Password

Illegal Password <%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %> The password "" is too short; it must contain at least six characters. Here is a possible password: .

Please try again.

**

29 Apache Struts:Beans www.coreservlets.com

Step 6 (Display Results in JSP)

Third Possible Page

**

Success

You have registered successfully. <%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %>

Email Address:

Password:

Congratulations

**

Example 1: Results (Initial Form)

33 Apache Struts:Beans www.coreservlets.com

Example 1: Results

(Legal Address and Password)

Using the JSP 2.0 Expression

Language with Struts

  • Pros
    • The JSP 2.0 EL is shorter, clearer, and more powerful
  • Cons
    • The bean:write tag filters HTML chars
    • There is no EL equivalent of bean:message
    • The EL is available only in JSP 2.0 compliant servers
      • E.g., Tomcat 5 or WebLogic 9, not Tomcat 4 or WebLogic 8.x
      • JSP 2.0 compliance list: http://theserverside.com/reviews/matrix.tss
  • To use the EL, use servlet 2.4 version of web.xml:
    • You also must remove the taglib entries **

… **

35 Apache Struts:Beans www.coreservlets.com

Struts Example: Confirmation

Page (Classic Style)

**… Congratulations. You are now signed up for the Single Provider of Alert Memos network! <%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %>

First name:

Last name:

Email address:

Fax number:

…**

Struts Example: Confirmation

Page (JSP 2.0 Style)

**… Congratulations. You are now signed up for the Single Provider of Alert Memos network!

First name: ${contactFormBean.firstName} Last name: ${contactFormBean.lastName} Email address: ${contactFormBean.email} Fax number: ${contactFormBean.faxNumber}

…**