Discussion Wap
You often need to verify that users have checked at least one choice from a set of checkboxes or selected one or more options from a select list. Both of these validations can be performed using the Validator's predefined required rule. However, validating users who have chosen more than one item requires a custom rule like the one shown in the Solution. You create the minchoices rule using the same basic steps outlined inRecipe 8.7. The rule requires that the validated field must be an array...
Solution Kiy
Use Niall Pemberton's Lazy DynaBean forms available for download from Declare the form-bean to use in the struts-config.xml lt form-bean name LazyForm Then, use the form on a JSP page as you would a normal ActionForm. Example 5-8 shows a JSP page lazy_form_test.jsp that will utilize the LazyForm declared previously. Example 5-8. Using the LazyValidatorForm on an HTML form lt page language-'java gt lt taglib prefix html gt lt taglib prefix bean gt lt html gt lt head gt lt title gt Struts...
Discussion Gma
Though the Validator offloads much of your hand-written code to a configuration file, more complex validations may be required. Two general types of validation exist syntactic and semantic. Syntactic validation verifies the syntax of the data, and semantic validation verifies that the data is meaningful from a business sense. The Validator does syntactic checks well but isn't purposed for semantic validation. Usually, this validation needs to be hand-written. Fortunately, the Validator doesn't...
Accessing Complex Properties with JSTL
More interesting in Example 3-17 is how the JSTL expression language EL is used to retrieve the collection of IDEs for the chosen language language The power of EL allows you to access normal JavaBean properties as well as mapped properties in almost any combination. To understand how the expression is evaluated, let's examine how it would be done in Java Map ideMap languageChoices.getLanguageldeMap get the selected language from the form bean DynaActionFrom form DynaActionForm String language...
Discussion Ige
The typical Action returns an ActionForward from itsexecute method. The returned ActionForward is evaluated and processed by the Struts request processor. The returned forward specifies the path to a resource, like a JSP page, that generates the actual HTTP response. However, you can generate the response in the Action. If you do so, you must returnnull from the Action's execute method. This tells the Struts request processor no ActionForward will follow therefore, the response should be...
Example Rendering a Tiles definition in a JSP page
lt taglib prefix-'tiles gt lt tiles insert definition mainLayoutDef gt lt tiles put name title type string value-'Start Page gt lt tiles put name body lt tiles insert gt Here's another JSP page view_page_one.jsp that uses the same definition lt taglib prefix-'tiles gt lt tiles insert definition mainLayoutDef gt lt tiles put name title type string value Page One gt lt tiles put name body lt tiles insert gt With Tiles, you reduce the amount of HTML that you have to cut and paste. More...
Example Decorator for a popup window
lt taglib prefix-'decorator decorator gt lt html gt lt head gt lt title gt lt decorator title default Unknown Page - shouldn't see this, since pages should define title gt lt link href lt request.getContextPath gt decorators main.css rel stylesheet type text css gt lt pulls the header from the page we are decorating and inserts it here -- gt lt decorator head gt lt head gt lt div class popupDiv gt lt span default Unknown Title - shouldn't see this gt lt span gt lt br gt lt -inserts the body of...
Example Overriding the processActionPerform method
import javax.servlet.ServletException import javax.servlet.http.HttpServletRequest import javax.servlet.http.HttpServletResponse import javax.servlet.http.HttpSession import import public class CustomRequestProcessor2 extends RequestProcessor protected ActionForward processActionPerform HttpServletRequest request, HttpServletResponse response, Action action, ActionForm form, ActionMapping mapping throws lOException, ServletException HttpSession session request.getSession User user User if user...
Example Simple JWebUnit test case
package com.oreilly.strutsckbk.ch13 import net.sourceforge.jwebunit.TestContext import public class SimpleWebTest extends WebTestCase public SimpleWebTest String name super name public void setUp throws Exception TestContext testContext getTestContext Use the message resources properties file testContext. setResourceBundleName public void testAppAvailable beginAt index.jsp use the title text from the testContext resource bundle You can run this test using any of the JUnit test runners. Like any...
Example Service factory plugin
package com.oreilly.strutsckbk.ch10 import javax.servlet. ServletException import org.apache.struts.action.ActionServlet import org.apache.struts.action.Plugln import public class ServiceFactoryPlugin implements Plugln public void init ActionServlet servlet, ModuleConfig config throws ServletException ServiceFactory factory new ServiceFactory factory. servlet.getServletContext factory public void setSecurityService String securityService this.securityService securityService
Example Label value bean Digester rules
lt object-create-rule pattern lv-beans classname-'java.util. Array List gt pattern lt object-create-rule classname org.apache.struts.util. LabelValueBean gt lt set-properties-rule gt lt set-next-rule methodname add gt lt pattern gt lt digester-rules gt Finally, add a plug-in declaration to yourstruts-config.xml for each file to be parsed and loaded lt plug-in lt set-property property key value serverTypes gt lt set-property property-'configPath lt set-property property digesterPath You can now...
Example JSP dump of request session and context data
lt hr width 3px gt Debug lnformation lt br gt lt table border 1 width 50 class debug gt lt tr gt lt th colspan 3 lt b gt Request Parameters lt b gt lt th gt lt tr gt lt c forEach items paramValues var parameter gt lt tr gt lt td gt lt c out lt td colspan 2 gt lt c forEach var value lt textarea rows 2 cols 50 gt lt c out value value gt lt textarea gt lt c forEach gt lt td gt lt tr gt lt c forEach gt lt th colspan 3 lt b gt Header Values lt b gt lt th gt lt tr gt lt c forEach items header var h...
Thread Local Variables Explained
If you look at the filter in Example 10-11, it may appear that only on Hibernate session will be for the application because the session is held in a static THReadLocal variable. While it's true that there will be only oneTHReadLocal variable, that variable will hold multiple object instances, Hibernate sessions in this case. When an object is added to a THReadLocal variable via theThreadLocal.set method, that object is implicitly associated with the current thread. In that sense, a ThreadLocal...
Solution Ryp
1. Download the OJBMessageResources distribution from 2. Extract the ZIP file into a directory on your computer. 3. Copy the ojb-msg-res.jarf e from the ojb-message-resources dist folder into your application's WEB-INF lib folder. 4. Copy the properties, XML, and DTD files from the ojb-message-resources config folder to your application'ssrc folder. When you build your application, these files must be copied to the WEB-INF classes folder. 5. Create the tables to hold the Objec Relational Bridge...
Example Precipitation graph JSP
lt page language-'java gt lt taglib prefix-'bean gt lt taglib prefix-'logic gt lt taglib prefix c gt lt title gt Struts Cookbook - Chapter 04 lt title gt lt head gt lt body bgcolor white gt lt h2 gt Struts Cookbook Chapter 4 Examples lt h2 gt lt div align center gt lt hr gt lt h3 gt Color Bar Chart horizontal lt h3 gt lt jsp useBean id weeklyWeather lt table border 0 width 60 gt lt logic iterate id dayEntry name weeklyWeather property weekForecast gt lt tr gt lt td align right width 20 gt lt...
Example Retrieving a RowSetDynaClass from an Action
package com.oreilly.strutsckbk.ch05 import javax.servlet. http.HttpServletRequest import javax.servlet. http.HttpServletResponse import import org.apache.struts.action.Action import org.apache.struts.action.ActionForm import org.apache.struts.action.ActionForward import public class ViewUsersAction extends Action public ActionForward execute ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response throws Exception UserDao dao new UserDao RowSetDynaClass...
Example Context refresh action
package com.oreilly.strutsckbk.ch10 import java.util.Enumeration import javax.servlet.ServletContext import javax.serviet.http.HttpServietRequest import import org.apache.struts.action.Action import org.apache.struts.action.ActionForm import org.apache.struts.action.ActionForward import public class ContextRefreshAction extends Action public ActionForward execute ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response throws Exception String name...
Example Alternating table row colors using Struts
lt page language-'java gt lt taglib prefix bean gt lt taglib prefix logic gt lt html gt lt head gt lt title gt Struts Cookbook - Chapter 4 Tables lt title gt ,row1 background-color orange Odd row .rowO background-color yellow lt style gt lt head gt lt body gt lt jsp useBean id-'weeklyWeather lt table gt lt tr gt lt th gt Day ofWeek lt th gt lt th gt Chance of Precipitation lt th gt lt th gt Expected Precipitation inches lt th gt lt tr gt lt logic iterate id forecast indexld count name...
Example Overriding the processPreprocess method
import javax.servlet. http.HttpServletRequest import javax.servlet. http.HttpServletResponse import javax.servlet.http.HttpSession import import public class CustomRequestProcessorl extends RequestProcessor protected boolean processPreprocess HttpServletRequest request, HttpServletResponse response HttpSession session request.getSession User user User if user null try response.sendError 403, User not logged in catch lOException e log.error Unable to send response Ifyou need to use the Struts...
Example Display tag example
lt page language-'java gt lt taglib prefix-'display gt lt html gt lt head gt lt title gt Struts Cookbook - Chapter 4 Display Tag Example lt title gt lt style gt .even background-color orange .odd background-color yellow lt style gt lt head gt lt body gt lt h2 gt Display Tag Examples lt h2 gt lt jsp useBean id-'pagedData Paged Data gt lt display table id-'pres name pagedData.data sort list pagesize 10 defaultsort 3 gt lt display caption gt United States Presidents lt display caption gt lt...
Example Custom error handling by an Action
package com.oreilly.strutsckbk.ch09 import javax.servlet.http.HttpServletRequest import import org.apache.commons.beanutils. Property Utils import org.apache.struts.action.ActionForm import org.apache.struts.action.ActionForward import org.apache.struts.action.ActionMapping import org.apache.struts.action.ActionMessage import public class ValidatingLoginAction extends BaseAction public ActionForward execute ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse...
Example Main decorator JSP page
lt taglib prefix-'decorator decorator gt lt taglib prefix-'page gt lt taglib prefix bean gt lt taglib prefix html gt lt taglib prefix c gt lt html gt lt head gt lt title gt lt decorator title default Unknown Page - shouldn't see this, since pages should define title gt lt link href decorators main.css rel stylesheet type text css gt lt pulls the header from the page we are decorating and inserts it here -- gt lt decorator head gt lt head gt lt table width- 00 height 100 gt lt tr gt lt td id...
Chapter Internationalization
Recipe 12.1. Detecting Browser Language Settings Recipe 12.2. Sharing Message Resources with JSTL Recipe 12.3. Using an Application-Wide Locale Recipe 12.4. Changing Locale on the Fly Recipe 12.5. Creating Localized Messages from an Action Recipe 12.6. Displaying Locale-Specific Text Recipe 12.7. Displaying Locale-Specific Images Recipe 12.8. Supporting Character Sets Recipe 12.9. Localizing Look and Feel
Is the DispatchAction Safe
A common misconception is that the DispatchAction allows any method of your subclass to be called. In fact, the only methods that can be called are those that accept the same arguments as those passed to the execute method. However, the DispatchAction initially shipped with Struts 1.1 had a serious flaw because it didn't test if the method to call was the execute or perform method. This oversight opened the door for an accidental or malicious recursive call. This bug was identified and has been...
Discussion Avr
A sizeable percentage of web applications use a relational database for storing data. In an architecture that emphasizes separation of concerns, controller actions interact with the model through business objects, data transfer objects, and service-oriented interfaces. But sometimes it makes more sense to provide direct views of data in the database. The RowSetDynaClass provides an effective mechanism for accessing and retrieving data from JDBC result sets. This class, provided in the Jakarta...
Discussion Olr
The JPDA has made debugging Java applications much easier You can use any debugging tool you want independently of the application being debugged. JPDA allows you to debug a Java application running in a separate JVM on a remote server on your network. Your local JVM, running the debugger, connects to the remote JVM across the network using the host name and a known port. In the Solution, the address specifies the port. This approach works well when the two computers are the samefor example,...
Example Sidebar navigation JSP page
lt taglib prefix-'bean gt lt taglib prefix c gt lt html gt lt head gt lt title gt lt bean message lt script gt function popUp url var windowFeatures height 300 lt script gt lt head gt lt body gt lt br gt lt c url var url value main.do gt lt a href lt c out value ' url ' gt gt Main Page lt a gt lt c url var url value test.do gt lt a href lt c out value ' url ' gt gt Test Another Page lt a gt lt c url var url value summary.do gt lt a href lt c out value ' url ' gt gt Summary Example lt a gt lt...
Example Tiles definition for a tabbed layout
lt xml version 1.0 encoding ISO-8859-1 gt lt DOCTYPE tiles-definitions PUBLIC - Apache Software Foundation DTD Tiles Configuration 1.1 EN ,dtd gt lt - Tiles used for Recipe 14.1, 14.2, and 14.3 gt lt -- A base Tile gt definition name mainLayoutDef2 lt put name title value Struts Cookbook - Chapter 14 Tiles gt lt put name header lt put name navbar lt put name body type string gt lt put name news lt put name footer lt definition gt lt - Extensions of the base mainLayoutDef tile -- gt definition...
Figure Project structure with test directory
The easiest way to create a new JWebUnit test class is to subclass If you have been using your own extension of the JUnit TestCase and cannot subclass WebTestCase, you can delegate calls to the net.sourceforge.jwebunit.WebTester class. The source for the WebTestCase class shows how this is done. Example 13-11 shows a simple test case verifying that Vr ejsc-ch13 web application is up and running.
Solution Poy
Extend the Struts pre-built MappingDispatchAction only available in Struts 1.2 or later with your own subclass. Provide methods for each operation you wish to be callable. Each method should have the same signature as the execute method. The class shown in Example 6-8 provides three related operations create , update , anddelete . Example 6-8. MappingDispatchAction for related operations package com.oreilly.strutsckbk.ch06 import java.util.HashMap import java.util.Map import...
Figure Configuring Eclipse for debugging
Clicking the Debug button will attach to the remote JVM. Figure 13-5 shows the Eclipse Debug perspective here, the breakpoint has been set within the Struts RequestProcessor. Figure 13-5. Eclipse debug perspective Figure 13-5. Eclipse debug perspective The latest IDEs have made debugging easier. If you debug using System.out.println calls, logging messages, and educated guessing, learn how to use a debugger. It will save you hours, you'll learn about your application's internals, and you'll...
Figure Failed run of a JWebUnit test case
Every JWebUnit test has a test context. This context, typically configured in the setUp method, contains information applicable to the test case such as the base URL. In Example 13-11 this value was set to the web application's context You can use JWebUnit to test the internationalization features of your web application. The test context allows you to specify the resource bundle for your localized text as well as the locale being tested. JWebUnit looks up properties from the resource bundle...
Typographical Conventions
The following typographical conventions are used in this book Plain text Indicates menu titles, menu options, menu buttons, and keyboard accelerators such as Alt and Ctrl . Indicates new terms, URLs, email addresses, filenames, file extensions, pathnames, directories, and Unix utilities. Indicates commands, options, switches, variables, attributes, keys, functions, types, classes, namespaces, methods, modules, properties, parameters, values, objects, events, event handlers, XML tags, HTML tags,...
Discussion 1
Using and examining the struts-example web application is an excellent learning aid for Struts. Before you write your first Struts application, you should understand how the struts-example application works. The best way to do this is to deploy the application. Experiment with the interface and take the walking tour. You will want to follow along in the walking tour by using your text editor or IDE to view the source code. You will need to download the Struts binary and source distributions to...
Discussion Vvs
While Struts 1.1 was a significant change to Struts 1.0, functionally speaking, applications based on Struts 1.0 can be migrated without much difficulty by replacing the Struts 1.0 JARs and TLDs with the corresponding files for Struts 1.1. You will need to change your use of the tag library URIs, as they have changed in Struts 1.1 this generally means changing your web.xml deployment descriptor. If you use the absolute URIs in your JSP pages, these values will need to be changed as well. Table...








