11/25/2007
Struts Best Practices
1
I
1
11/25/2007
Sang Shin
sang.shin@sun.com www.javapassion.com Java™ Technology Evangelist Sun Microsystems, Inc.
2
2
11/25/2007
Disclaimer & Acknowledgments
?
?
?
Even though Sang Shin is a full-time employees of Sun Microsystems, the contents here are created as their own personal endeavor and thus does not reflect any official stance of Sun Microsystems. Sun Microsystems is not responsible for any inaccuracies in the contents. Acknowledgments:
– –
Some slides are created from "Jakarta Struts: Seven lessons from trenches" article written by Chuck Cavaness Some slides are created from "Struts Best Practices” article written by Brijesh Deb
3
3
11/25/2007
Revision History
? ?
July 2nd, 2005: version 1: created by Sang Shin Things to do
4
4
11/25/2007
Extend Only When Needed
?
Make sure extending the framework is the last resort
–
Extending framework would add maintenance cost
5
.
5
11/25/2007
Use Declarative Exception Handling
?
?
Struts framework includes a class called ExceptionHandler that by default is responsible for processing any exceptions that occur during action execution The default Struts exception handler class creates an ActionError object and stores it in the appropriate scope object
6
.
6
11/25/2007
Use Application Modules
?
? ?
In a multi-developer environment, a single struts-config.xml is a bottleneck Allows parallel development Necessary for large scale applications
7
.
7
11/25/2007
Protect JSP Pages
?
? ?
Protect your JSP pages from unauthorized access or viewing Front your JSP pages with Struts Actions Two options
– –
Store your pages in a directory that is below the Web application's WEB-INF directory Use security feature of Web application
8
It's very typical for JSP developers to keep their pages in subdirectories under the Web application root. For example, Figure 2 shows a typical directory structure for a storefront application. The JSPs relating to catalog are placed in the catalog subdirectory under the storefront directory. The same might be true for the customer JSPs, order JSPs, and so on. The problem with this approach is that these pages are a little more susceptible to a user being able to view the source of the JSPs, or at least call the JSP directly. In some cases, this might not be a huge issue, but under certain circumstances it can be a security risk. It could also present a problem if users are allowed to circumvent the Struts controller by invoking a JSP directly. To reduce this risk, you can move the pages into a directory underneath WEBINF. Based on the Servlet specification, WEB-INF is not part of the public document tree of the Web application. Therefore, no resource within the WEBINF directory (nor those beneath it) may be served directly to a client. We can still use JSPs stored underneath the WEB-INF to render views for a client; however, a client may not request one of the JSPs directly. This helps to protect your site from unwanted access and at the same time, allows you to render views using JSPs.
8
11/25/2007
Protect JSP's Behind WEB-INF
?
Suppose we had an Action mapping in Struts configuration file for a logoff action, the path must include /WEB-INF
9
Once the JSPs are located underneath the WEB-INF directory, you must use "WEB-INF" as part of the URL when referencing the pages. For example, suppose we had an Action mapping in our Struts configuration file for a logoff action. The paths to JSPs must include WEB-INF at the beginning.
The only trick with using this approach, which is good practice with Struts in any case, is that you should always front your JSPs with a Struts action. Even if the Action is a very basic JSP, you should always call an Action that in turn invokes the JSP.
9
11/25/2007
Protect JSP's using Security Features of Web application
?
Nobody can access JSP pages directly
... no_access *.jsp ...
10
Once the JSPs are located underneath the WEB-INF directory, you must use "WEB-INF" as part of the URL when referencing the pages. For example, suppose we had an Action mapping in our Struts configuration file for a logoff action. The paths to JSPs must include WEB-INF at the beginning.
The only trick with using this approach, which is good practice with Struts in any case, is that you should always front your JSPs with a Struts action. Even if the Action is a very basic JSP, you should always call an Action that in turn invokes the JSP.
10
11/25/2007
Use the Prebuilt Actions
?
Struts framework comes with several prebuilt Action classes that can save a tremendous amount of development time and reduce the number of files to manage
– –
org.apache.struts.actions.ForwardAction org.apache.struts.actions.DispatchAction
11
The Struts framework comes with several prebuilt Action classes that can save a tremendous amount of development time. The most beneficial of these are the org.apache.struts.actions.ForwardAction and the org.apache.struts.actions.DispatchAction.
11
11/25/2007
Use DynaActionForm's
?
Allow you to configure an ActionForm completely through the Struts configuration file
–
There's no longer a need to create actual concrete ActionForm classes in your application
?
Helps to facilitate automatic presentationlayer validation
12
.
12
11/25/2007
Use Struts Tools
? ? ? ? ? ? ?
Adalon (Commercial) Easy Struts (Open source) Struts Console (Free) JForms (Commercial) Camino (Commercial) Struts Builder (Open source) StrutsGUI (Free)
13
.
13
11/25/2007
Categorize Errors
?
?
To display the error messages of different categories, define these categories such as FATAL, ERROR, WARNING, or INFO, in an interface In the Action or form-bean class, you can then use the following
– – – – –
errors.add("fatal", new ActionError("....")); or errors.add("error", new ActionError("....")); or errors.add("warning", new ActionError("....")); or errors.add("information", new ActionError("....")); saveErrors(request,errors);
14
Struts' ActionErrors class comes in handy in resolving the first issue of stacking messages of different categories. To display the error messages of different categories, define these categories such as FATAL, ERROR, WARNING, or INFO, in an interface. Then, in the Action or form-bean class, you can use: errors.add("fatal", new ActionError("....")); or errors.add("error", new ActionError("....")); or errors.add("warning", new ActionError("....")); or errors.add("information", new ActionError("....")); saveErrors(request,errors);
14
11/25/2007
Categorize Errors
?
To display them according to those categories, use the following code:
Or use:
showError(''); // JavaScript
15
Struts' ActionErrors class comes in handy in resolving the first issue of stacking messages of different categories. To display the error messages of different categories, define these categories such as FATAL, ERROR, WARNING, or INFO, in an interface. Then, in the Action or form-bean class, you can use: errors.add("fatal", new ActionError("....")); or errors.add("error", new ActionError("....")); or errors.add("warning", new ActionError("....")); or errors.add("information", new ActionError("....")); saveErrors(request,errors);
15
11/25/2007
Create Common Action Class
?
When common operations need to be included in all the actions, create common Action class
–
An example of such a requirement in an Online Shopping application would be to perform user authorization before processing all user requests
?
Make all other Action classes extend the common action class to centralize the handling of common operations and reduce code redundancy
16
.
16
11/25/2007
Create Common Action Class
Public abstract class BaseApplicationAction extends Action { public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { try { //Call all common methods performAuthorization(); return executeSpecificTask(mapping,form,request,response); } catch(Exception ex){//exception} } // Authorization is an operation common through all the application actions private void performAuthorization() { //Code for user authorization } //Provide implementation of this method in sub-classes public abstract ActionForward executeSpecificTask(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception } 17
.
17
11/25/2007
Handle Duplicate Form Submission
?
?
The problem of duplicate form submission arises when a user clicks the Submit button more than once before the response is sent back or when a client accesses a view by returning to a previously bookmarked page. Handle it by using the saveToken() and isTokenValid() methods of Action class
– –
saveToken() method creates a token (a unique string) and saves that in the user's current session isTokenValid() checks if the token stored in the user's current session is the same as that was passed as the request parameter.
18
.
18
11/25/2007
Handle Duplicate Form Submission
public class PurchaseOrderAction extends DispatchAction { public ActionForward load(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { try { //save the token saveToken(request) // rest of the code for loading the form } catch(Exception ex){//exception} }
19
.
19
11/25/2007
Handle Duplicate Form Submission
public ActionForward submitOrder(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { try { // check the token. Proceed only if token is valid if (isTokenValid(request,true)) { //implement order submit functionality here } else { return mapping.findForward("failure"); } } catch(Exception ex){ } } }
20
.
20
11/25/2007
Transaction Tokens
Michael Rimov & Craig McClanahan
11/25/2007
What is a Transaction Token?
A Transaction Token is a string-based token used to ensure that a form is not submitted twice. The token must be generated prior to the evaluation of the
that will use it.
Michael Rimov & Craig McClanahan
11/25/2007
Using a Transaction Token
Struts Provides 2 methods of generating a token: • Using the Action.saveToken(request) method • Using the transaction attribute of an
tag
Michael Rimov & Craig McClanahan
11/25/2007
Using a Transaction Token (html:link)
Adding the transaction attribute to the
tag referencing the JSP containing the
.
Add a New Employee
Michael Rimov & Craig McClanahan
11/25/2007
Using a Transaction Token (html:link)
When the
tag is evaluated it adds a query parameter to the link.
Add a New Employee
Michael Rimov & Craig McClanahan
11/25/2007
Using a Transaction Token (html:form)
When the previous link is selected, it will load an
tag that will contain a hidden input tag with the previously generated token.
Michael Rimov & Craig McClanahan
11/25/2007
Using a Transaction Token (Action)
if ( isTokenValid(request) ) { // valid token do something } else { //the transaction was already submitted return (mapping.findForward("resubmitted")); }
Michael Rimov & Craig McClanahan
11/25/2007
Use Single ActionForm for Similar Forms
?
?
?
For similar forms, use a single ActionForm that includes all possible fields instead of having several ActionForms This is generally applicable to different forms required to implement the same use case It leads to easy maintenance, though all the fields will be not be used for all the Actions
28
.
28
11/25/2007
Use Single ActionForm for Similar Forms
?
For example, in the Online Shopping application we can use a single ActionForm (CustomerProfileForm) for different forms related to customer profile management (like DisplayCustomerProfile.jsp, EditCustomerProfile.jsp, etc.)
29
.
29
11/25/2007
Use global-forwards to Avoid Redundant forwards
? ?
Helps to avoid mentioning for all the actions The Online Shopping application should display the login page in case of session timeout. Instead of including for all the actions, add a single entry in the strutsconfig.xml to throw the login.jsp to the user in case of session timeout encountered in any Action, like this:
30
.
30
11/25/2007
Remove ActionFrom From Session
?
?
If ActionForm is set to session scope, it should be removed from session whenever it's utility is over In the sample online shopping application, in case of the multi-screen customer registration, if the RegistrationForm is set to session scope, it should be removed form the session once the user clicks Cancel
31
.
31
11/25/2007
Use Business Delegate
?
?
Action should not implement complex business functionalities, rather delegate these to the Model Use Business Delegate to talk to the Business tier and the Data Tier
32
Action should not implement complex business functionalities, rather delegate these to the Model. Use Business Delegate to talk to the Business tier and the Data Tier.
32
11/25/2007
Avoid instance/static Variable in Action Class
?
Instance and static variables should not be used in an Action class to store information related to the state of a particular request.
–
The same instance of an Action class can be shared among multiple simultaneous requests through multi-threading
?
Instance/static variable may however be used to share global resources across requests for the same action.
33
.
33
11/25/2007
Do Not Include Business Logic in ActionForm
?
ActionForm represents HTML form(s) and it is used by Struts to transfer data between View and Controller
– –
They should not be treated as part of the Model Do not include any business functionality in the reset() or validate() method of ActionForms as this would lead to tight coupling of application business functionality with the presentation tier (implemented through the Struts framework).
34
.
34
11/25/2007
Use html:messages (instead of html:errors
?
For displaying error messages to the end user, use
instead of
–
If you are using , you have to have your html markup language in your resource file
35
.
35
11/25/2007
Use StrutsTestCase For Unit Testing
?
?
Because StrutsTestCase uses the ActionServlet controller to test the code, you can test not only the implementation of your Action objects, but also the mappings, form beans, and forwards declarations. StrutsTestCase provides both container testing and simulated container testing to actually run the Struts ActionServlet, allowing you to test Struts code with or without a running servlet engine.
36
StrutsTestCase is an extension of the standard JUnit TestCase class that provides facilities for testing code based on the Struts framework. Because StrutsTestCase uses the ActionServlet controller to test the code, you can test not only the implementation of your Action objects, but also the mappings, form beans, and forwards declarations. Further, since StrutsTestCase provides validation methods, it is quick and easy to write unit test cases. StrutsTestCase provides both container testing and simulated container testing to actually run the Struts ActionServlet, allowing you to test Struts code with or without a running servlet engine. Refer http://strutstestcase.sourceforge.net/ for details.
36
11/25/2007
Passion!
37
37