44
Struts in Detail Mohan Bang

Struts presentation 2

Embed Size (px)

Citation preview

Page 1: Struts presentation 2

Struts in Detail

Mohan Bang

Page 2: Struts presentation 2

Agenda

• Overview of STRUTS

• A Look at a Simple Struts Example

• The Struts Tag Library

• Advanced Features of Struts

• New Features in Struts 1.2

• Working Example – Banking System

Page 3: Struts presentation 2

The Components of Struts

• Struts consists of two main components:1. The servlet processing portion, which is

responsible for maintaining control of user sessions and data, and managing workflow.

2. The tag libraries, which are meant to reduce or eliminate the use of Java scriptlets on the JSP page.

Page 4: Struts presentation 2

The Three Pieces of MVC

• The Model – The actual business data and logic, such as an class representing users in the database and routines to read and write those users.

• The View – A separate class which represents data as submitted or presented to the user on the JSP page.

• The Controller – The ringmaster who decides what the next place to take the user is, based on the results of processing the current request.

Page 5: Struts presentation 2

The Model

• The model isn’t part of Struts per say, it’s the actual back-end business objects and logic that Struts exposes to the user.

• In this case, we’ll write a very simple bean that implements a User object.

• Note: All example code omits imports for reasons of brevity..

Page 6: Struts presentation 2

package strutsdemo;

public class User {

private String username = null; private String password = null;

public String getUsername () { return username; } public void setUsername(String name) { username = name; }

public String getPassword () { return password; } public void setPassword(String pw) { password = pw; }

public static User findUser(String username) { User u = new User(); u.setUsername(username); u.setPassword(“test”); return u; }}

Page 7: Struts presentation 2

The Model (cont)

• No rocket science so far, the Model (in this case) is a simple bean with a dummied up load method that just creates a test user.

• The key point of MVC is that the model doesn’t get directly exposed to the view (the JSP page in Struts.)

• So how is data passed back and forth to the user?

Page 8: Struts presentation 2

Enter the View

• The view is an placeholder object used in association with the JSP pages, and which holds a temporary copy of the model.

• Why do this? Well, suppose you are editing a model object, and the form submission fails during validation.

• If the model = the view, the model is now in an inconsistent state and the original values are lost.

Page 9: Struts presentation 2

Defining the View

• With Struts 1.1, there are now two different ways to define a view object (known as an ActionForm)

• You can create a bean manually, with manual form validation.

• Or you can use DynaBeans in combination with the Validator Framework.

Page 10: Struts presentation 2

A Manual ActionForm

package strutsdemo.struts.forms;

public class UserForm extends ActionForm {

private String username = null; private String password = null;

public String getUsername () { return username; } public void setUsername(String name) { username = name; }

public String getPassword () { return password; } public void setPassword(String pw) { password = pw; }

Page 11: Struts presentation 2

A Manual ActionForm (cont)

public ActionErrors validate(ActionMapping map, HttpServletRequest req)

{

ActionErrors errors = new ActionErrors();

if ((username == null) || (username.size() == 0)) {

errors.add(“username”,

new ActionError(“loginform.username.required”));

}

if ((password == null) || (password.size() == 0)) {

errors.add(“password”,

new ActionError(“loginform.password.required”));

}

return errors;

}

}

Page 12: Struts presentation 2

Key Points for ActionForms

• In general, all fields should be Strings.

• This preserves the contents of the field if it doesn’t match against the required type (so if you type in “1OO” for a field that needs to be a number, the field contents will be preserved when it returns to the input form.)

Page 13: Struts presentation 2

More on ActionForms

• If an ActionForm doesn’t implement Validate, the default one (which does nothing) is run.

• If an ActionForm overrides Validate, it controls whether a form passes validation or not. If the ActionErrors object returned has size > 0, control is returned to the input page.

Page 14: Struts presentation 2

A Common ActionForm

• Let’s say you have a boolean property called isJavaGeek tied to a checkbox on a page.

• You submit the form with the checkbox checked.

• Then you hit the back button (or it returns to the page because of a validation error), and you uncheck the box.

Page 15: Struts presentation 2

A Common ActionForm

• The problem: Because by the HTML standard, unchecked checkboxes don’t get placed on the request, the form object will not get the new value because the reflection will never occur to change the value of isJavaGeek

• The solution: Implement the reset() method on the ActionForm.

Page 16: Struts presentation 2

Using Struts on the JSP Page

• Let’s take a look at the input form that supplies our newly created ActionForm with values

• Struts uses the struts-html taglib to make interacting with the view easy.

Page 17: Struts presentation 2

login.jsp<%@ page language=“java” %>

<%@ taglib uri=“/WEB-INF/struts-html.tld” prefix=“html” %>

<head><title>Log in Please</title></head>

<h1>Log In Please</h1>

<html:form action=“/login”>

<html:errors property=“username”/><BR>

Username: <html:text property=“username”/><BR>

<html:errors property=“password”/><BR>

Username: <html:password property=“password”/>

<html:submit/>

</html:form>

Page 18: Struts presentation 2

Controlling Flow with Actions

• The actual processing of forms occurs in Actions.

• The action is the link between the view and the backend business logic in the model.

• The action is also responsible for determining the next step in the workflow.

Page 19: Struts presentation 2

A Simple Action Class

package strutsdemo.struts.actions;

public class LoginUserAction extends Action {

public ActionForward execute(ActionMapping mapping,

ActionForm form,

HttpServletRequest req,

HttpServletResponse resp) {

UserForm uf = (UserForm) form;

User u = User.findUser(uf.getUsername());

ActionErrors errors = new ActionErrors();

if (u == null) {

errors.add(“username”,

new ActionError(“loginform.username.notfound”));

}

if (!uf.getPassword().equals(u.getPassword()) {

errors.add(“password”,

new ActionError(“loginform.password.invalid”));

}

Page 20: Struts presentation 2

A Simple Action Class (cont)

if (errors.size() > 0) {

saveErrors(request, errors);

return mapping.getInputForward();

}

request.getSession().setAttribute(“currentUser”, u);

return mapping.findForward(“success”);

}

}

Page 21: Struts presentation 2

A Note About Validation

• Because the ActionForm shouldn’t contain business logic, the Action may need to do some validations (such as username/password checking)

• Since the Action isn’t called until the ActionForm validates correctly, you can end up getting new errors at the end of the process.

Page 22: Struts presentation 2

Tying it All Together

• So far, you’ve seen all the components that come together to form a Struts request cycle, except…

• The piece that ties all the disparate pieces together.

• In Struts, this is the struts-config.xml file.

Page 23: Struts presentation 2

A Simple Example of the Config

<struts-config>

<form-beans>

<form-bean name=“userForm” type=“strutsdemo.struts.forms.UserForm”/>

</form-beans>

<action-mappings>

<action path=“/login” name=“userForm” scope=“request” validate=“true”

type=“strutsdemo.struts.actions.LoginUserAction”

input=“/login.jsp”>

<forward name=“success” path=“/mainMenu.jsp”/>

</action>

</action-mappings>

</struts-config>

Page 24: Struts presentation 2

Things to Notice in the Config

• For space reasons, the XML header was omitted.

• Form-beans define a name that Struts uses to access an ActionForm.

• Actions define:– What path the action is associated with.– What JSP page provides the input.– What JSP pages can serve as targets to the Action.– What Action is used to process the request.– Whether the form should be validated.

Page 25: Struts presentation 2

Built in Security

• Because all JSP pages are reached via calls to Actions, they end up with URLs like “/login.do”

• The end-user never sees the actual URL of the underlying JSP page.

• You can place access control in your Actions, avoiding having to put checks on all your JSP pages.

• You can also use container-based security to control access via roles directly in the config.

Page 26: Struts presentation 2

The Struts Tag Libraries

• With the exception of the HTML and TILES libraries, they have all been superceded by JSTL.

• However, if you can’t move to a Servlet 2.3 container, they offer a lot of the power of JSTL.

Page 27: Struts presentation 2

Examples of Struts Tags

<logic:iterate id=“person” name=“people”> <logic:empty name=“person” property=“height”> <bean:write name=“person” property=“name”/> has no height<BR> </logic:empty></logic:iterate>

Page 28: Struts presentation 2

The Struts Tag Libraries

• Logic – Conditional Display, Iteration

• Bean – Data Instantiation and Access

• Html – Forms and Links

• Nested – Access to Properties of Beans

• Tiles – Structured Layout of Pages

Page 29: Struts presentation 2

Advanced Tricks with Struts

• DynaForms allow you to avoid writing ActionForms alltogther.

Page 30: Struts presentation 2

<form-bean name=“userForm” type=“org.apache.struts.actions.DynaActionForm”>

<form-property name=“username” type=“java.lang.String”/>

<form-property name=“password” type=“java.lang.String”/>

</form-bean>

DynaActionForm uf = (DynaActionForm) form;

String userName = (String)uf.get(“username”);

Page 31: Struts presentation 2

How to Validate DynaForms

• Since you don’t define DynaForms as explicit classes, how do you do validation?

• Answer 1: Extend the DynaActionForm class and write validate() methods.

• Answer 2: Using the Struts Validator Framework.– Based on the Commons Validator package.

– Uses an XML file to describe validations to be applied to form fields.

Page 32: Struts presentation 2

The Validator Framework

• Predefined validations include:– Valid number: float, int– Valid Credit Card– Length Checks– Blank/NotBlank– Regular Expression Matches– Plus the all-purpose cross-field dependency:

requiredif

Page 33: Struts presentation 2

<form name=“medicalHistoryForm"> <field property=“lastCheckup“ depends=“required">

<arg0 key=" medicalHistoryForm.checkup.label"/>

</field><field property=“weight“ depends=“required,float">

<arg0 key=" medicalHistoryForm.weight.label"/>

</field></form>

Page 34: Struts presentation 2

New Features in STRUTS 1.2

• Wildcard Mappings

• Intro of ValidWhen in Struts Validator

• ActionError(s) and ActionMessage(s)

• Deprecated init param entries in web.xml removed

• TagUtils introduced instead of RequestUtils

• Many of the deprecated tag attributes removed

Page 35: Struts presentation 2

Wild Card Mappings

• Wildcard mappings allow you to define a generic set of mappings that can be used across all actions that follow a common workflow pattern and naming convention – For Eg:<action path="/Edit*"

type="com.oreilly.strutsckbk.ch07.Edit{1}Action" name="{1}Form" scope="request" validate="false">

<forward name="success" path="/edit_{1}.jsp"/> </action>

Page 36: Struts presentation 2

Explanation

• Now when I have an action path like http://com.oreilly.struts/myapp/EditUser.do, the Struts RequestProcessor matches the wildcarded mapping to the URL; the {1} represents the text that matches the wildcard (*) (similar to a capture group in a regular expression). So you end up with the following "virtual" mapping:

Page 37: Struts presentation 2

<action path="/EditUser"

type="com.oreilly.strutsckbk.ch07.EditUserAction"

name=“userForm"

scope="request"

validate="false">

<forward name="success" path="/edit_user.jsp"/>

</action>

Page 38: Struts presentation 2

• Validwhen appears in Struts 1.2

<form name=“medicalHistoryForm"> <field property=“lastMamogram“

depends="validwhen"> <arg0

key="dependentlistForm.firstName.label"/> <var> <var-name>test</var-name> <var-value>((gender=“M”) OR (*this* != null)) </var-value> </var> </field></form>

if you want to start using the new validwhen validation rule, then you will need to deploy the antlr.jar as well

Page 39: Struts presentation 2

Validwhen contd

• if you want to start using the new validwhen validation rule, then you will need to deploy the antlr.jar as well

Page 40: Struts presentation 2

ActionError(s) and ActionMessage(s)

• ActionError IS deprecated and should be replaced by ActionMessage.

• ActionErrors IS NOT deprecated. The Struts committers would have liked to have deprecated ActionErrors but because too much of core API depend on it (such as the ActionForm's validate method) it hasn't been. However it may be in the future and, where possible, you should now use ActionMessages in place of ActionErrors.

Page 41: Struts presentation 2

<init-param> web.xml configuration • A number of the of init parameter entries (i.e. <init-param>) in

the web.xml were marked as deprecated in the Struts 1.1 release and have been removed in Struts 1.2

• mapping - see note on configFactory below • debug - replaced by Commons Logging • bufferSize - moved to <controller> element in the struts-config.xml • content - renamed to contentType and moved to <controller> element in the

struts-config.xml • locale - moved to <controller> element in the struts-config.xml • maxFileSize - moved to <controller> element in the struts-config.xml • nocache - moved to <controller> element in the struts-config.xml • multipartClass - moved to <controller> element in the struts-config.xml • tempDir - moved to <controller> element in the struts-config.xml • application - now parameter in the <message-resources> element in the struts-

config.xml • factory - moved to <message-resources> element in the struts-config.xml • null - moved to <message-resources> element in the struts-config.xml

Page 42: Struts presentation 2

Custom Tags and Validation

• Many methods in org.apache.struts.util.RequestUtils and org.apache.struts.util.ResponseUtils are deprecated. Replace RequestUtils.* and ResponseUtils.* with org.apache.struts.taglib.TagUtils.getInstance().*

• Replace org.apache.commons.validator.ValidatorUtil with org.apache.commons.validator.util.ValidatorUtils.

Page 43: Struts presentation 2

Summary

• Current version of Struts 1.3 is about to be released.

• Supported by all major IDEs (Eclipse, IdeaJ, Jbuilder, etc)

• Widely accepted and integrated into most J2EE platforms.

• Want to learn more? “We’ve seen no better resource for learning Struts than Struts

Kick Start. “ -- barnesandnoble.com

Page 44: Struts presentation 2

Thank You