>> Delivering Value
Struts 2.0 Session - 4 May, 2009 Presentation By Training & Development
Introduction Good Evening Guys! Welcome back to the Struts 2 training program. We have crossed three days of training but have seen only a little of struts
There is a lot to learn Today we will be delving deeply into Struts 2. Let us start with random recaps:
2
Mr. Thinker What are the attributes of HTTP?
HTTP is stateless and text based
3
Mr. Thinker What are the main problems with Servlets?
Separation of Concern is nonexistent. HTML code is embedded in Java making it difficult to maintain
4
Dumbo Vs. Jumbo Jumbo! Does JSPs completely replace Servlets?
No Dumbo. JSPs still get converted to Servlets. So, for each JSP we see, there will be a corresponding servlet in the background
5
Mr. Thinker What are the problems with JSPs?
Separation of concern is still a problem. Java code is embedded in HTML which is equally undesirable
6
Mr. Thinker What is the View layer generally made of?
View Layer is generally implemented using JSPs
7
Dumbo Vs. Jumbo What puzzle does MVC solve?
Separation of concerns. The three layers are totally separated
8
Mr. Thinker How do Filters help?
Repetitive tasks can be moved to a Filter. (Eg. Session checking, authentication etc)
9
Mr. Thinker How is dependency injection achieved generally?
Dependency Injection is achieved generally by performing Setter Injection.
10
Dumbo Vs. Jumbo Command Pattern is basis of what framework?
Command Pattern is the basic building of Struts Framework
11
Mr. Thinker What is the ancestor framework of Struts2?
Webwork
12
Mr. Thinker Who authored Struts
Craig Mc Clanahan
13
Dumbo Vs. Jumbo Web Work is based on what Framework?
X Work
14
Mr. Thinker X Work implements which design pattern?
Command Pattern
15
Dumbo Vs. Jumbo What is the minimum java requirement to use Struts 2?
You should be having at least java 1.5
16
Mr. Thinker What are the advantages of Struts 2? (whatever we have realized till now?)
No request. get parameters, no type conversions, no forwards/redirects, etc
17
Ms. Natasha It is time to move on guys! I leave the dais now to the trainer to continue with Day 4 contents
18
The Internals of the Ph.D. Project
19
Using an MVC Design pattern without Struts JSP
Web.xml
Servlet
Find out the servlet that will serve the request
(Request.getparame ter, business logic, Forward to result JSP etc)
Result JSP
20
Using Struts 2 JSP
Web.xml Find out the servlet that will serve the request
Result JSP
Struts.xml
Filter Dispatcher
Struts.xml
This is a filter
Action Class (Execute business logic)
A MAGIC BOX
21
Dumbo Vs. Jumbo Now I know why he talked about Filters yesterday
Let us listen to him and see what he has to say about Filters in Struts 2
22
Web.xml As with any web application, the request first goes to web.xml In web.xml, the request is mapped to a Filter The request reaches the Filter
23
Filter Dispatcher This is a Filter This is the entry point to the Magic World called Struts 2 This initiates the request processing life cycle
24
Struts.xml The Filter Dispatcher reads the Struts.xml to find out which action class /
method needs to be invoked
Once this information is available, the Filter Dispatcher initiates the request
processing life cycle
25
The Magic Box The magic box does a lot of things We entered our name, first number and second number in the screen and
suddenly and automatically these values are available in the Action Class without our intervention
We never wrote request.getparamter!! we never did explicit type conversion
to float values
That is why we called it a Magic Box We will explain in more detail about this Magic Box and its actual name very
shortly
26
Action Class We already saw this. This is a normal java class which need not even extend
any other class
This is just a POJO Some of the points to note in the action class – The action class contains a method called execute – The action class contains class level variables for each corresponding
HTML fields (Eg. myName, firstNumber, secondNumber) – These class level variables follows javabeans specifications and has setter/getter methods – The action returns a String generally which is checked with the name attribute of the result element in the struts.xml for the corresponding action element. The result element decides on the target page based on the value of name attribute
27
The Return Journey After the successful execution of business logic in action class, the
framework checks the struts.xml to see which page should be displayed
The framework now displays the result jsp
28
Dumbo Vs. Jumbo In the above explanation, I saw Filters but not even a single servlet. Struts 2 does not support servlets?
Cool Man !
Not exactly. The framework provides a Filter which is basically the part of the Controller layer. It is just that instead of servlet it provides Filter. Nothing serious. But in a Struts 2 application you are free to have servlets if you want doing whatever you would like. No constraints from the framework. Am I clear?
29
Exploration of the Magic Box - Interceptors
Hi! Are you available for a date tonight?
You are my villain. I am going to change your request…..
#@$@#$@# $???
Mr. Interceptor Hi! Are you available for a date tonight?
Mr. William Khan
Is there any body else more dumb than you!!”
Ms. Anne Davis 30
Dumbo Vs. Jumbo I cannot imagine that Struts 2 can do such destructive things. So, interceptors are basically like viruses that mutate your request and make it look different. Am I correct?
Not exactly. You have got it totally wrong. Only the example taken was like that. Interceptors are the friends of Struts 2 developers. Interceptors are used for constructive purposes. Our trainer will explain more
31
Interceptor Pictorially
As you can see from the above picture, interceptors are part of the
controller layer
The filter invokes the various interceptors
32
What are interceptors? Interceptors are normal Java classes Interceptors are conceptually similar to Filters In other words interceptors are used for providing pre-processing / post-
processing functionality around the action classes
The purpose of interceptors is to remove cross cutting tasks from the action
class and move them to separate class called Interceptors
Typical examples: – Getting the values of the screen fields and moving them to model
variables (i.e. request.getparameter) – Converting the type of screen fields from String to the corresponding type of the model – Similarly converting the type of model variables back to string when displaying the values in the screen – A lot more 33
A good API Reference on Interceptor http://struts.apache.org/2.x/docs/interceptors.html
34
What are interceptors? (Contd.) Interceptors are concepts of XWork framework on top of which Sturts2 has
been built
Interceptors are of two types – Interceptors that come built in with the framework – Custom Interceptors – Interceptors that can be written totally by you
35
Dumbo Vs. Jumbo I am slowly coming to terms. question.
But I have a
<SAMPLE>
36
Configuration of Interceptor Interceptors are generally per action Hence it should be configured at the same location where actions are
configured. i.e. in struts.xml
/HelloWorldSuccess.jsp
37
Exercise In the Hello World Project, add the interceptor in struts.xml as
mentioned above and see the behavior after running it in browser – Observe the log (Tomcat 6.0) in the Net Beans window at the bottom – you would observe that the name of the action is displayed in the logs – Run the HelloWorld.jsp and you would observe that the name does not get displayed
38
Dumbo Vs. Jumbo Till I did the exercise it was totally clear to me. I was assuming that the framework did a lot of things like setting screen variables to the action variables etc. But now I am so confused. I just introduced an interceptor element in struts.xml and it immediately introduced a bug that whatever name I enter, it does not get displayed in the results page. What a shame?
There is a reason for everything. Struts is not so buggy mind you. The trainer will explain more on the background of this behavior
39
Explanation For This Behavior Of course it is clear that the purpose of logger interceptor is to record log
messages in the console and hence you see details regarding the action name etc in the log files
But how does introducing the logger interceptor introduce a bug like
behavior?
It should now be clear to you that configuring logger interceptor overrode a
setting that was already present
That is nothing but the “default” behavior. We just overrode the default
behavior. So the default behavior was no more available
40
Dumbo Vs. Jumbo I understood but where do I set the default behavior? Is the setting built in? if I want to reset the default behavior to some other settings is there no way to do it?
A good question. The answer is “Yes, there is a way”. If you open struts-core-2.0.14.jar, there will be a file called “struts-default.xml”. This is the most important file that we should refer to understand the internals. Here you will find a setting like this <default-interceptor-ref name="defaultStack"/> This is where the default is specified. If you want to override this value with a different default, it can very well be done in struts.xml itself
41
Dumbo Vs. Jumbo You are unbelievable man! It is so crystal clear for me now. However, I see the term Stack being mentioned. Is there any significance attached to it?
A good question again. There is significance. Let us continue to listen to the trainer to know more.
42
Interceptor Stack One action can be associated with multiple interceptors So, in the action configuration you can specify multiple interceptors Example:
43
Dumbo Vs. Jumbo That’s fine. But in the above case, what is the order of execution? I hope the order of execution might matter in many cases
Yes the order matters. The order of execution is the order in which the interceptors are declared in the struts.xml under the action element. So, in the above example, first logger interceptor will be executed, then exception, alias, servlet config and prepare. Am I clear?
44
Dumbo Vs. Jumbo Yes, you are. Thank you. But my original question of what is the significance of the term Stack still remains unanswered.
Yes, he is coming there
45
Interceptor Stack (Contd.) OK, now that there is a way to configure multiple interceptors for a given
action, the concept of stack is just an extension of this.
Instead of defining the interceptors one by one in the action element, an
interceptor stack can be defined
The interceptor stack can then be used in action definitions So, in our example, the implementation would be like this:
46
Interceptor Stack (Contd.)
/HelloWorldSuccess.jsp
47
Dumbo Vs. Jumbo Its all fine. But I heard that interceptors are normal Java Classes. But where I see there is just the interceptor name. But where is the reference to the actual java class. How does the framework know which java class to execute for a particular interceptor? WoW!
Today is your day. You have been asking all gem of questions. The answer is again struts-default.xml. There is an element called interceptors under which the following is a typical interceptor definition:
In the above, class is the java class that will be executed whenever a logger interceptor is referred 48
Mr. Thinker The interceptor-ref element’s name attribute can refer either to an interceptor or a stack also
All interceptor stack definitions and interceptor definitions should be under the element called
49
Mr. Thinker The interceptor-stack element can in turn contain other stacks as well
50
Exercise Dumbo has been jumping all over about a bug Your goal is now to make the Hello World project work well again A very difficult Hint: – Define a stack using logger and default Stack – Then refer this new stack in your action definition – I am tough guy. You can never get easy clues from me
51
Exploration of the Magic Box – OGNL / Value Stack Interceptors, Value Stack and OGNL are the three most important concepts of Struts 2 If you become a master in these three, you will be a master of Struts 2. We have already seen an overview of Interceptors. Now let us concentrate our energy on Value Stack and OGNL
52
Exploration of the Magic Box – OGNL / Value Stack PAGE DEVELOPER
I have put the Purchase Order Object into the session, Invoice Object into the request scope, asset object into the application scope. You can take them from the corresponding scope and then display it on the screen Oh my God! Is he mad or what? He has just scattered the objects all over the place. Now I need to get the objects from the corresponding scope and then display it in the screen. So, I should be using, request.getattribute, session.getattribute etc. Poor Me!! BUSINESS LOGIC DEVELOPER 53
Value Stack to your rescue The Page Developer’s concern is very valid. There might be a reason behind
the Business Logic Developer putting the variables in various scopes. But it would be great if the page developer can just retrieve them without bothering about the scope
Value Stack is exactly for that purpose Value Stack is exactly what it says it is – a stack of objects It is just a centralized data store which can be referred by the various layers
of the framework
54
Value Stack Constituents The value stack consists of the following objects in the provided order – Temporary Objects – Model Object – Action Object – Named Objects
Application Session Request
TEMPORARY OBJECT MODEL OBJECT ACTION OBJECT NAMED OBJECT
55
How does Value Stack work? If you want the attribute “name”, then you query the value stack for this
attribute.
Each stack element, in the provided order, is asked whether it has the
property.
If it does, then the value is returned and we are done. If not, then the next element down is queried. This continues until the end of the stack is reached.
56
Advantages of Value Stack • As evident from the above discussion, the main advantage of value stack is
that you don’t care where the value is – the action, the model, or the HTTP request – you just know that if the value exists it will be returned.
57
Accessing Value Stack – OGNL The objects in the value stack are accessed by what is called OGNL OGNL is the acronym for Object Graph Notation Language OGNL is an expression language It is used for getting and setting the properties of Java Objects
58
A Very Simple Example Assume that we have an action class called “MyAction” Inside that we have an object called “person” with getter and setter methods Inside Person class there is an object called “address” with getter and setter
in Person Class
Inside Address class we have attributes called city, state, zipCode etc and
corresponding getters and setter methods
59
A Very Simple Example
CITY ADDRESS PERSON MY ACTION VALUE STACK
60
A Very Simple Example (Contd.) Now I want to retrieve and display the city attribute in the JSP The city is retrieved as follows: – person.address.city – Internally OGNL converts this to getPerson( ).getAddress( ).getCity( ); – Please note that we do not explicitly state anywhere that the person
object is in the action class called MyAction – It is automatically detected by the OGNL in the value stack In a nutshell, this is how you would write in JSP – <s:property value="%{ person.address.city }"/>
61
Dumbo Vs. Jumbo Wow!! Man. This is really interesting. I didn’t know that it would be that easy. If not for these value stack, ognl etc my life would have been tough. I should have retrieved the Person object either from request or session object and then manually invoked the gettters inside these objects. Now I am really beginning to appreciate the magic of Struts 2
This is just the beginning. There is still a lot more to go. Wait and Watch.
62
Dumbo Vs. Jumbo In one of the previous sessions we talked about Romeo and Juliet. I think it was about a concept called Dependency Injection. Was it just for fun?
If you use your brain you would realize it that we have already learned Dependency injection in Struts 2 just now. The Magic Box / Interceptor does just that.
63
Interceptor
ParamsInterceptor
setMyName (String myName) My Action 64
Interceptor (Contd.) Is this not dependency injection? This is called Setter Injection. The action class just provides a setter method but it expects somebody else
to set the value to this variable called myName
Promptly the Interceptor does exactly that. The ParamsInterceptor sets the
myName variable by invoking the setter method of the action class
In one of the future sessions we will also see about another type of
dependency injection
65
Exercise • The objective is to capture Address Details of a Person and display
them back
My Name
Street
City
Street
Zip Code
Address
The details of the model are given above Perform the following; – Create a JSP page for capturing the person details including the
address – Display another JSP to display the captured details back to the user as labels – You should be knowing what you need to do internally to make this happen 66
Dumbo Vs. Jumbo That was easy Jumbo. I have a question now. I have done a few exercises and I am already getting bored with the method name execute. This method as I understand is the most important method that does all the business logic execution. Is there a freedom for me to name it as I want?
Thanks. That would help. Good.
T hat’s a good question. You are not alone. Many developers feel a little bored to have the same name. More importantly if I need to use the same action class for two business logic methods then I have a problem because I cannot name both of them as execute We have a solution for this. You can name the business methods as doSomething( ) or even something( ). public String doSomething( ) { .. .. return “SUCCESS”; In the action element definition in struts.xml, /someresult.jsp 67
Exercise • Change the name of the action method as createAddress instead of
execute ( ) and do the other changes required to make it work
68
Session 4 We are coming to the end of an interesting session on Struts. Now we are really into Struts I am sure the trainer has more to offer to you in the next sessions. We look forward to meeting you all in the next session Till then its bye from all here
69
Session 4 Thank You !
70