Sunteți pe pagina 1din 67

>> Delivering Value

Struts 2.0
Session - 6

June, 2009

Presentation By
Training & Development
Introduction
Good Evening everybody!
Welcome back to the Day 6 of
the Struts 2 training course

2
Introduction
• Day 1 – History of Web applications
It will be another
exciting day of learning. • Day 2 – Concepts to be known before
Let us now do a quick learning Struts 2
recap on what we have
learned so far: • Day 3 – Struts 2 environment setup,
Hello World Project, PhD Project
• Day 4 – Dissection of Hello World,
Value Stack, OGNL
• Day 5 – Action Interface, Action
Support class, Validation, Resource
Bundle and Internationalization
• Let us now let Thinker, Dumbo and
Jumbo refresh your memory by
providing reviews of important points
over the past week
3
Mr. Thinker
Yes Filters can act on pre-
Can filters act on both request as well as post-
request and response? response.

4
Dumbo Vs. Jumbo
Lets see, whether you can say this Jumbo, What
are annotations?

Annotations are syntactic form of metadata.


Annotations are added to the Java Source Code.
Annotations are not method calls

5
Mr. Thinker

What is the problem that


Decoupling the sender of a
Command pattern attempts to
command from the receiver of
solve?
the command. The sender does
not know anything specific
about the intricacies of the
command handled by the
receiver

6
Dumbo Vs. Jumbo
Web Work is based on what Framework?

X Work

7
Mr. Thinker

X Work implements Command Pattern


which design pattern?

8
Mr. Thinker

No request. get parameters,


What are the advantages no type conversions, no
of Struts 2? (whatever we forwards/redirects, etc
have realized till now?)

9
Dumbo Vs. Jumbo
What is the name of the interface that our
action classes can implement?

Action

10
Mr. Thinker
ActionSupport class
What is the name of the
class that already
implements Action and few
other interfaces and that
which is of huge utility to
developers?

11
Mr. Thinker

Action, Validateable,
What are the interfaces ValidationAware,
that ActionSupport TextProvider,
implements? LocaleProvider

12
Dumbo Vs. Jumbo
Action interface contains how many methods
and what are their names?

Just one method


called execute

13
Dumbo Vs. Jumbo
Name some constants defined by Action
Interface

ERROR,
INPUT,
SUCCESS etc

14
Mr. Thinker

What are these These are used as return


used for? strings of execute /
validate / other business
logic methods

15
Mr. Thinker

By invoking
How do you add an addActionError method
action level error
message?

16
Mr. Thinker

By invoking
How do you add a addFieldError
field level error method
message?

17
Dumbo Vs. Jumbo
What are the parameters for addFieldError
method?

The field name (as


specified in JSP) and
the error message

18
Dumbo Vs. Jumbo
What should be the name of the result (or the
return string) in case of validation errors?

Input

19
Dumbo Vs. Jumbo
What is the tag that should be added for the
errors to be displayed in the JSP

<s:actionerror />

20
Mr. Thinker
params
What is the name of the
interceptor that transfers
data from the screen fields
to the action fields?

21
Mr. Thinker
Workflow
What is the name of the
interceptor that invokes the
validate method of the action class
and acts according to the result of
the validate method? (either pass
the control back to the page or
invoke the action method)

22
Mr. Thinker

What is the name of the doIntercept


method in any interceptor
that always gets invoked
during the request processing
chain?

23
Dumbo Vs. Jumbo
To which interface does the interceptor’s doIntercept
method type cast the action class to check for any
errors?

ValidationAware

24
Mr. Thinker

To which interface does the Validateable


interceptor’s doIntercept
method type cast the action
class to invoke the validate
method?

25
Mr. Thinker

What is the name of the file struts.propertie


that provides details about s
the resource bundle file etc

26
Dumbo Vs. Jumbo
Where are action errors displayed in the page?

In the top of the page

27
Dumbo Vs. Jumbo
Where are field errors displayed in the page?

Above the corresponding


field

28
Ms. Natasha

Unbelievable!! You guys are of


immense help to us in this
training. Now go back to your
abode. We will let the trainer
start today’s session

29
Exercise
 Run the latest project (Address Capture) and provide a string value
for Salary
 Observe the behavior

30
Dumbo Vs. Jumbo
Well, not without a reason. I did not do any checking but
automatically I get an error in the page complaining about the
string that I entered!! Is this also the power of struts?

Yes of course. This is part of the automatic type conversion that happens
in Struts. Salary is of type float or double. There is an interceptor called
“conversionError” which checks the conversions to java types and spits
out any conversion type errors. In our case, we have entered a string
value for salary. Since there is a mismatch between the types, the error is
automatically thrown. Please also note that the conversionError is
located after the params interceptor which is responsible for transferring
the data from screen to action class. OK, now let us move on to today’s
topic, the Validation Framework

31
Struts 2 - Validation Framework

32
Introduction
• We have already discussed about one form of validation which is using a
validate method inside the action class. Let us now focus our attention on a
complete framework provided by Struts for Validation

33
Various ways of Validation in Struts 2
 Automatic type conversion validation – (automatically provided by
Framework)
 validate method in action class

 validation Framework

We have already covered the first two aspects. Now let us look into the
Validation Framework provided by Struts 2

34
Constituents of the Validation Framework
– Domain Data – Data to be validated
– Validators – Classes provided by framework which actually performs the
validation
– Validation meta data – the component that wires domain data with
validators

35
Constituents of the Validation Framework
(Contd.)
 As depicted in the above picture, there are various validators provided by the
framework each developed for a specific purpose
– required
– requiredstring
– int
– date
– double
– etc

 Domain Data are the actual data that need to be validated. Most of the
cases, this is the data available in the action classes
 Validation Meta data can be one of the two:
– An XML file
– Annotated Java Source

36
Constituents of the Validation Framework
(Contd.)
 Validation Meta data is the layer that wires a particular data with a particular
validator
 For example if Salary is mandatory then the meta data can be used to wire
this field with the validator called required

37
Exercise

 Let us learn the validation framework, the hard


way. Yes, through an exercise
 Our objective is to do the following validations in
the Address Capture application:
– Name is mandatory
– Age is mandatory

 Create a new XML file under the action


directory called “AddressAction-validation.xml”

38
Exercise
 Type the following inside this XML:

 <!DOCTYPE validators PUBLIC "-


//OpenSymphony Group//XWork Validator
1.0.2//EN""http://www.opensymphony.com/xwork/
xwork-validator-1.0.2.dtd">
<validators>
<field name="person.myName">
<field-validator type="requiredstring">
<message>
Name is mandatory
</message>
</field-validator>
</field>
</validators> 39
Exercise

 Clean, build and run the Address Capture Application

 Click submit button without entering any value in the


Name field
 You will get a validation error in the screen with
respect to the name field

40
Dumbo Vs. Jumbo
Again for me, it looks like a magic. What happened internally,
I am at a loss to understand

Yes, I agree. Let us give some time to the trainer to explain this

41
Internals of the validation framework
 In a nutshell what we did
– Created an XML file named <Action Class>-validation.xml
– In the XML, attached a particular field to a particular type of validator
– Already provided a result with name=input
– Already provided the tag <s:actionerror/> in the JSP

 Let us now learn in detail about validation framework


– <interceptor-ref name="params"/>
– <interceptor-ref name="conversionError"/>
– <interceptor-ref name="validation"/>
– <interceptor-ref name="workflow"/>

42
Internals of the validation framework (Contd.)

 The above is a set of interceptors defined in struts-default.xml

 All of us know that params interceptor is for transferring data from the
form fields to value stack
 conversionError is for displaying error messages with respect to conversion
of data types from screen to java types
 The last interceptor, the workflow interceptor is the one who was
responsible for invoking the validate method in the action class, do you
remember?
 Now the only interceptor left out is the validation interceptor in bold above

 As it is evident, validation interceptor is invoked after conversion error and


before workflow
 This is the interceptor which is responsible for invoking the <action class>-
validation.xml to check for any validation as mentioned in the XML
43
Dumbo Vs. Jumbo
The explanation was good. OK. But why should I use this approach
But he did not tell me the when I already have the validate method
purpose of this XML. in the action class? Why cannot I
always use the validate method in the
action class?

Not smart. There


are so many Well, I thought it is self-explanatory. This
advantages of XML wires one or more input fields with one
using the XML or more validators. For example, in the
framework. Our above example, the field myName was wired
trainer will explain with the validator called “requiredstring”.
you in more detail Similarly there can be many fields and many
in the next slide validators in this XML

44
Advantages of XML approach to validation
 Validation is externalized and not part of the action class

 Less coding and just a matter of seconds before you wire any validator for
any field
 Supports field level as well as form level validations

 Generally all field level validations can be handled in the XML validators and
the validate method of action class is generally meant for complex
validations involving multiple fields and business logic

45
Dumbo Vs. Jumbo

If there are validation errors how does the framework route me


back to the same page

Whether it is this approach or the validate method approach, the


framework checks for any errors using hasErrors method of
validationAware interface. (that means any errors are added to the
instance of ValidationAware interface). If there are errors, then a result
with name “input” is passed back and hence the input page is displayed

46
Dumbo Vs. Jumbo

OK. Is it possible that both the XML validation and the


validate method get executed simultaneously so that the user
gets to know all the error messages at once rather than one by
one?

Yes. Perfect

Good question. Yes, in fact, that is the default behavior of the


framework. Even if there are errors in validation done through XML, the
framework proceeds with the invocation of the validate method in action
class. Only then it routes the page back to the user’s page. Am I clear?

47
Exercise

 Create one more input field in the screen called


email
 Check whether the email entered is valid. If not,
throw an appropriate error message
 Email is a mandatory field

 Name should be a minimum of 3 characters in


length

48
Exercise
– I am a tough guy. You know. So, you are
going to be in soup. I will give a tough hint
– liame dellac epyt rotadilav esu

 Hint 1:
– Read the above sentence from right to left to
get a hint
 Hint 2:
– For Name, use a validator type of stringlength
– You should use a param with
name=minLength
49
Dumbo Vs. Jumbo
I have a question. What if I have two validations for a
particular field. Is there a way I can have multiple
validations for a particular field?

Yes, it is possible. Just have multiple field-validator


elements under the field element. As simple as that.

50
Dumbo Vs. Jumbo
By the way, in the previous example, the param was very
useful for minLength of name. But the only problem is that I
hardcoded the message that the length should be minimum 3
characters. Is there a way I can take that value from the
variable itself instead of hardcoding?

A very valid question. And the answer is yes. You can use
the variable in the message like this. “The name should be
minimum of ${minLength} characters”. As you would have
guessed, the minLength is an OGNL expression enclosed
within ${ }

51
Exercise

 In the previous exercise do not hard code the


number 3. Instead get the value from the variable
itself

52
Dumbo Vs. Jumbo
Cool Man. One more question. Is there a way I can
mention the value of a particular field in the message?
For example I want to call out the name of the person
before I display the error.

Yes, it is possible. Just like ${minLength}, you can use


any form field’s value in the XML. You can enclose them
in ${ } and it should work fine.

53
Exercise

 In the previous exercise display the message like


this: “Hi <Name>! The Name should be
minimum of <minLength> characters.

54
Mr. Thinker

How do I represent
Embed the
OGNL in a JSP
expression within %{
}

55
Mr. Thinker

How do I represent Embed the


OGNL in a expression within ${
validation XML? }

56
Dumbo Vs. Jumbo
Initially we talked about i18n and how struts 2 supports
it. But in this XML again we are hard coding the
message!! What’s up?

A very good catch. But Struts 2 has a way out. Instead


of <message></message>, you can use <message
key=‘msg.key’/> which will then look in the properties
file with a key as ‘msg.key’.

57
Exercise

 In the previous exercise retrieve the message


from the message bundle instead of hard coding

58
Dumbo Vs. Jumbo
Till this point, we have only looked into validations
which are specific to a field. What about validations
which span multiple fields? Or validations which contain
an expression? Does Struts 2 support this?

Yes, Struts 2 supports expression inside validations. Let


us see an example

59
Expressions in Validations
 <validator type="expression">

 <param name="expression">person.age > 10</param>


 <message key="address.age.10.error"/>
 </validator>

 The above is an example of expressions in validations

 The above validation checks if age is greater than 10. If less than or equal
to 10, an error is displayed
 Please note that the expression inside the param is the expression for PASS.
If the expression returns false, then an error is displayed

60
Exercise

 Do the above change in the latest exercise that


you completed

61
Mr. Thinker

For all my previous


Because this is an
validations, the
action scope message
errors were displayed
whereas all the
above the field. But
previous messages were
for this error is
field scoped messages
displayed at the top!!

62
Dumbo Vs. Jumbo
One last question for the day. Why did I create the
validation XML inside action directory? Is there any
specific reason?

The validation XML is loaded by the class loader. Hence


we created that file under the same location where you
have action classes

63
Dumbo Vs. Jumbo

Sorry one more last question  If I have more than one


action represented in an action class, (i.e. more than one
business logic method), will I be able to have one xml for
each of these business methods?

I know you are talking about a case similar to the


validate method in action class (like how we have one
“validatedo” method for one action method). Yes it is
possible. Let the trainer explain.

64
Multiple validations for same action class
 To create multiple validations file (one for each business method), the
following should be the name of the validation XML:
 <Action Class Name>-<action name>-validation.xml

 In this case, depending on the action name the corresponding validation.xml


will automatically be invoked

65
Session - 6

Guys! We are making steady


progress. Today we looked into
the validation framework in great
detail. We will see you all
tomorrow with another great topic

66
Session 6

Thank You !

67

S-ar putea să vă placă și