Implementing mobile WebSphere Commerce

This tutorial will take you through an implementation of WebSphere® Commerce storefront for a mobile device. It will show how to create a servlet filter to detect the device used and then map to a specific Struts action. It will also show how to cache based on the device format.

Mike Callaghan, WebSphere Commerce Support Analyst, IBM

Author1 photoMike Callaghan is a Software Developer at the IBM Toronto Lab, Canada. He has been part of the WebSphere Commerce Support team since 2005, specializing in runtime components. He was also part of the DB2 Development Infrastructure team, specializing in UNIX scripting and automation. He graduated with Honors from McMaster University, Canada, with a Bachelor's degree in Software Engineering


developerWorks Contributing author
        level

N Krishnan (nkrishna@in.ibm.com), WebSphere Commerce Consultant, IBM

Author photoN Krishnan is an IT Specialist working at the IBM India Software Labs, India. He was part of the WebSphere Commerce development team and currently working as a consultant in IBM Software Services for WebSphere. He was also part of developing retail solutions in the Retail EBO team.



Nicolai Nielsen (nicolai.nielsen@uk.ibm.com), WebSphere Commerce Consultant, IBM China

Photo of Nicolai NielsenNicolai Nielsen is a Senior IT Specialist at IBM Hursley Software Lab, United Kingdom. He has been with the WebSphere Commerce Technology Practice of IBM Software Services for WebSphere since 2006. Before that, he worked as a WebSphere Commerce consultant with IBM Global Services Denmark.



03 June 2009

Before you start

The current trend in online shopping has retailers targeting customers wherever they are, whichever device they are on, rather than being restricted to a traditional desktop. You will go through one implementation of WebSphere Commerce specifically for a mobile device. This tutorial highlights many of the key concepts of how to use the WebSphere Commerce Struts framework to support different displays for each mobile device. You will learn to implement a servlet filter to detect each device and then map it accordingly to a new Struts action. You will also force the display type based on your preference. Finally, you will learn how to cache the pages based on the device format.

Objectives

  • Implement a servlet filter to detect the type of device submitting the request.
  • Create views for specific devices.
  • Switch between mobile and non-mobile views on the storefront.
  • Use Dynacache to cache the views based on device type.

Prerequisites

This tutorial is intended for WebSphere Commerce developers. Knowledge of Struts, strorefront JSPs, and servlet filters is useful, but not required.

System requirements

This tutorial requires the use of a mobile device simulator to test the results. You will need to find a simulator, for example, by searching for one via the Internet. We used an Apple® iPhone® simulator in our practice. The assumption is that the simulator allows you to enter a URL from the local server. This tutorial will provide the URLs to enter into the mobile device simulator.

This tutorial will also assume an IBM WebSphere Commerce Developer v6.0 environment is being used. There is no dependent fixpack or feature pack level.

The out-of-the box ConsumerDirect sample store is used throughout the tutorial.

Duration

2 hrs

Getting started

Extract the provided MobileCommerceCode.zip to a temporary location because you will reference this location as MobileCommerceCode\ from now on.


Inspecting the ConsumerDirect store from a mobile device

In this first part of the tutorial, you will browse the ConsumerDirect starter store using a typical browser. These views are then accessed using a mobile device simulator to get an idea of how the standard starter store renders in such a device. This justifies the need to have views specifically for each device type.

Before making any modifications to ConsumerDirect, examine the AdvancedSearchView in a typical browser. Do the following to display the ConsumerDirect catalog search page:

  1. Start the IBM WebSphere Commerce Developer from your Windows® Start Menu.
  2. When the application is started, right-click the WebSphere Commerce Test Server and select Start.
  3. When the server is started, open a standard Web browser and enter the following URL in the Address field:
    http://localhost/webapp/wcs/stores/servlet/ConsumerDirect/index.jsp
  4. The ConsumerDirect language selection page appears. Click United States English.
  5. The TopCategoriesDisplay page appears (Figure 1).
  6. Click ADVANCED SEARCH in the top right of the header.
  7. The AdvancedSearchView page appears (Figure 2). In the remaining part of the part of this tutorial, you will modify this view to fit a smaller display resolution.
  8. Enter search criteria of "chair" in the "Search for" text box and click the SEARCH button. This takes you to the CatalogSearchResultView (Figure 3). In the remaining part of the part of the tutorial, you will modify this view to fit this mobile device screen.

Figure 1 shows the TopCategoriesDisplay for ConsumerDirect in a standard browser, which will be modified throughout this tutorial to display on a mobile device.

Figure 1. ConsumerDirect TopCategoriesDisplay in a standard browser
ConsumerDirect TopCategoriesDisplay in a standard browser

Figure 2 shows the AdvancedSearchView for ConsumerDirect in a standard browser, which will be modified throughout this tutorial to display on a mobile device.

Figure 2. ConsumerDirect AdvancedSearch in a standard browser
ConsumerDirect AdvancedSearch in a standard browser

Figure 3 shows the CatalogSearchResultView for ConsumerDirect in a standard browser, which will be modified throughout this tutorial to display on a mobile device.

Figure 3. ConsumerDirect CatalogSearchResultView in a standard browser
ConsumerDirect CatalogSearchResultView in a standard browser

Now that you have seen the out-of-the-box (OOB) search view and search results view in a standard browser, you will view these same views in a mobile device simulator:

  1. Ensure the WebSphere Commerce Test Server within IBM WebSphere Commerce Developer is started.
  2. Open the mobile device simulator you have decided to use in your browser.
  3. In the simulator, enter the following URL in the Address field:
    http://localhost/webapp/wcs/stores/servlet/ConsumerDirect/index.jsp
  4. The ConsumerDirect language selection page appears. Click United States English.
  5. The Top Categories page appears (Figure 4).
  6. Click in the store window, hold and scroll to the right. Click ADVANCED SEARCH in the top header.
  7. The AdvancedSearchView page appears (Figure 5). In the remaining part of the part of the tutorial, you will modify this view to fit on a smaller display that would be on a mobile device.
  8. Enter a search criteria of "chair" in the "Search for" text box and click the SEARCH button. This takes you to the CatalogSearchResultView (Figure 6). In the remaining part of the part of the tutorial, you will modify this view to fit on a smaller display on a mobile device.

Figure 4 shows the TopCategoriesDisplay for ConsumerDirect without modification on a mobile device simulator in Safari.

Figure 4. ConsumerDirect default TopCategoriesDisplay in a mobile device simulator on Safari
ConsumerDirect default TopCategoriesDisplay in a mobile device simulator on Safari

Figure 5 shows the AdvancedSearchView for ConsumerDirect without modification on a mobile device simulator in Safari.

Figure 5. ConsumerDirect default AdvancedSearchView in a mobile device simulator on Safari
ConsumerDirect default AdvancedSearchView in a mobile device simulator on Safari

Figure 6 shows the CatalogSearchResultView for ConsumerDirect without modification on a mobile device simulator in Safari.

Figure 6. ConsumerDirect default CatalogSearchResultView in a mobile device simulator on Safari
ConsumerDirect default CatalogSearchResultView in a mobile device simulator on Safari

Adding a servlet filter

In this part of the tutorial, you will add and configure a servlet filter. This filter inspects the user agent header of the client. If it recognizes the User-Agent as a known mobile device, it instructs WebSphere Commerce to use a predefined mobile device format for that request. This filter allows a view specific to each device-type.

Create MobileDeviceServletFilter class

Now create a new servlet filter. The servlet filter pre-processes and post-processes any Web request by intercepting the request (or response).

We have created a sample servlet filter. You can import it into your workspace with the following steps:

  1. From the J2EE perspective of Rational Application Developer, expand WebSphereCommerceServerExtensionsLogic > src.
  2. Right-click src and select New > Package.
  3. Leave the Source Folder as default, and enter com.wstc.filter as the Name for the package.
  4. Click Finish.
  5. To import the new filter, right-click the com.wstc.filter package you just made and click Import.
  6. On the Import wizard, select File system and click Next.
  7. From directory, click Browse and navigate to MobileCommerceCode\Part3\3.2\ and click OK.
  8. Select MobileDeviceServletFilter.java in the right panel to import this class.
  9. Leave the other fields as default values. Click Finish.
  10. Ignore the warning related to any unused Imports - you will be using those in a later step.
  11. Expand src > com.wstc.filter > MobileDeviceServletFilter.java to open the file for editing.
  12. Inspect the init() method to see how to construct the HttpAdapterDesc objects:
    public void init(FilterConfig arg0) throws ServletException {
     //Http Browser (standard browser): DEVICEFMT_ID = -1
     browserHttpAdapterDesc = new HttpAdapterDesc();
     browserHttpAdapterDesc.setDeviceFormatName("BROWSER");
     browserHttpAdapterDesc.setDeviceFormatId(new Integer(-1));
     browserHttpAdapterDesc.setDeviceFormatType("BROWSER");
     browserHttpAdapterDesc.setDeviceFormatTypeId(new Integer(-1));
    
     //I mode (mobile device): DEVICEFMT_ID = -2
     iHttpAdapterDesc = new HttpAdapterDesc();
     iHttpAdapterDesc.setDeviceFormatName("MOBILE");
     iHttpAdapterDesc.setDeviceFormatId(new Integer(-2));
     iHttpAdapterDesc.setDeviceFormatType("MOBILE");
     iHttpAdapterDesc.setDeviceFormatTypeId(new Integer(-2));
      }

    Notice how you are creating two HttpAdapterDesc objects, which provide details on the different types of adapters to use. You are building one for the standard browser and one for a mobile device browser.

    Note: This tutorial uses DEVICEFMT_ID = -2. This may conflict with an existing custom device you already have. It is not necessary to use -2 for the mobile device, but this tutorial uses DEVICEFMT_ID for consistency.

  13. Inspect the doFilter() method to see how to create the SRTServletRequest object, and then retrieve the User-Agent from the HTTP headers of this object. The User-Agent maps to the device (or browser) used to make the servlet request.
    if (request instanceof SRTServletRequest) {
    	SRTServletRequest serRequest = (SRTServletRequest) request;
    
    	// Check for the User-Agent in the HTTP Header of the Servlet
    	// Request
    	String header = serRequest.getHeader("User-Agent");
    	String device = null;
    
    	//Wrap the response and request objects so we can play with the
    	// cookies
    	HttpServletResponseWrapper resp = new HttpServletResponseWrapper(
    		(HttpServletResponse) response);
    
    	HttpServletRequestWrapper req = new HttpServletRequestWrapper(
    		(HttpServletRequest) request);
    		 
    	//The current User-Agent we detect from the HTTP Header
    // TODO:  REMOVE after testing is complete or use WAS Logger for logging purposes
    	System.out.println("===DEBUG=== User-Agent: " + header);
    	}

In the next step, you still need to map the User-Agent to the browser adapter objects, which you made earlier.

Map User-Agent to browserAdapterDesc objects

The filter so far intercepts the servlet request and detects the User-Agent found in the header of this request. Now you will map the User-Agent to a browser adapter, which, in the simple example, will be either a BrowserAdapterDesc object for Mobile-device or a standard browser.

  1. From the J2EE perspective of Rational Application Developer, expand WebSphereCommerceServerExtensionsLogic > src > com.wstc.filter > and double-click MobileDeviceServletFilter.java if it is not already open.
  2. Open a text editor and open the file MobileCommerceCode\Part3\3.3\snippet1.txt.
  3. Inspect the code and check the header for known User-Agents and to map to a specific adapter.
    // Lets just detect the device
    if ((header != null) && (device == null)) {
    	System.out
    	 .println("===DEBUG=== We will auto-detect the User-Agent ");
    
    	//iPod
    	if (header.indexOf("iPod") > -1) {
    		device = new String("MOBILE");
    		RequestHandle handle = (RequestHandle) request
    		 .getAttribute(ECAttributes.ATTR_EC_REQUEST_HANDLE);
    		((HttpAdapter) handle.getDeviceAdapter())
    		 .setAdapterDesc(iHttpAdapterDesc);
    		System.out
    		 .println("===DEBUG=== User-Agent: Its iPod , set as Mobile!");
    				
    	//iPod Simulator / Safari
    	} else if (header.indexOf("Safari") > -1) {
    		device = new String("MOBILE");
    		RequestHandle handle = (RequestHandle) request
    		 .getAttribute(ECAttributes.ATTR_EC_REQUEST_HANDLE);
    		((HttpAdapter) handle.getDeviceAdapter())
    		 .setAdapterDesc(iHttpAdapterDesc);
    		System.out
    		 .println("===DEBUG=== User-Agent: Its iPod Simulator (Safari), 
              set as Mobile!");
    					
    	//Standard IE browser	
         } else if (header.indexOf("MSIE") > -1) {
    		device = new String("BROWSER");
    		System.out
    		 .println("===DEBUG=== User-Agent: Its Firefox! , 
             set as Standard Browser");
    
    	//Standard Mozilla Firefox browser
    	} else if (header.indexOf("Firefox") > -1) {
    		device = new String("BROWSER");
    		System.out
    		 .println("===DEBUG=== User-Agent: Its Firefox! , 
             set as Standard Browser");
    	}
    
    	// we do not know what it is, just default to using standard browser
    	else {
    		device = new String("BROWSER");
    		System.out
    		 .println("===DEBUG=== User-Agent: unknown type , 
             set as Standard Browser");
    	}
    
    }
    // set the device we will use for our struts global-forward
    // lookups
    
    // Standard Browser (default)
    if (device.equals("BROWSER")) {
    	RequestHandle handle = (RequestHandle) request
    	 .getAttribute(ECAttributes.ATTR_EC_REQUEST_HANDLE);
    	((HttpAdapter) handle.getDeviceAdapter())
    	 .setAdapterDesc(browserHttpAdapterDesc);
    	System.out.println("===DEBUG=== Setting to use BROWSER DEVICE");
    }
    // I Mode (Mobile device)
    else {
    	RequestHandle handle = (RequestHandle) request
    	 .getAttribute(ECAttributes.ATTR_EC_REQUEST_HANDLE }
  4. In MobileDeviceServletFilter.java, which is opened in your Rational Application Developer window, locate this line near the end of the file:
      //The current User-Agent we detect from the HTTP Header
    System.out.println("===DEBUG=== User-Agent: " + header);
  5. Copy and paste the entire contents of the snippet1.txt directly below this line. Ensure you paste above the closing brace from the earlier conditional statement. Close snippet1.txt.
  6. Save the changes to MobileDeviceServletFilter.java and leave it open to modify again later. Note that as you save this file in subsequent changes, the application will get restarted upon saving it.

Register MobileDeviceServletFilter to filter Stores Request Servlet

Now that you have created a new class to be used as a servlet filter, modify the deployment descriptor for the store's Web module (web.xml) to register the class as a filter.

  1. From the J2EE perspective of Rational Application Developer, expand Stores and double-click Deployment Descriptor: Stores to open it for editing.
  2. When the Web Deployment Descriptor opens, click the Source tab to modify the web.xml.
  3. Locate the following section in the source XML:
    <filter>
      <display-name>RuntimeServletFilter</display-name>
      <filter-name>RuntimeServletFilter</filter-name>
      <filter-class>com.ibm.commerce.webcontroller.RuntimeServletFilter</filter-class>
        <init-param>
         <param-name>ServletName</param-name>
         <param-value>Stores</param-value>
        </init-param>
    </filter>
  4. Paste in the following section after the above snippet to add the MobileDeviceServletFilter class as a new servlet filter, which will handle the request after the RuntimeServletFilter, but before the CacheFilter. You can also find this snippet under MobileCommerceCode\Part3\3.4\snippet2.txt.
          <filter>
          <display-name>MobileDeviceServletFilter</display-name>
          <filter-name>MobileDeviceServletFilter</filter-name>
          <filter-class>com.wstc.filter.MobileDeviceServletFilter</filter-class>
           <init-param>
            <param-name>ServletName</param-name>
            <param-value>Stores</param-value>
           </init-param>
          </filter>
  5. Locate the following section in the source XML:
          <filter-mapping>
           <filter-name>RuntimeServletFilter</filter-name>
           <servlet-name>Stores Request Servlet</servlet-name>
          </filter-mapping>
  6. Paste in the following section after the above snippet to add the MobileDeviceServletFilter filter mapping. This maps to the Stores Request servlet. You can also find this snippet under MobileCommerceCode\Part3\3.4\snippet3.txt.
          <filter-mapping>
           <filter-name>MobileDeviceServletFilter</filter-name>
           <servlet-name>Stores Request Servlet</servlet-name>
          </filter-mapping>
  7. Save and close the deployment descriptor.
  8. Optional: Compare your changes to a completed version of the web.xml, which you can find under MobileCommerceCode\Part3\3.4\web.xml.

Test the new servlet filter in a standard browser

You have created the MobileDeviceServletFilter class and registered it as a servlet filter for the Store's Web module. Now you will test the filter by accessing the ConsumerDirect store in a standard browser and inspect the console output to see the detected User-Agent.

  1. In WebSphere Commerce Developer, restart the WebSphere Commerce Test Server for the web.xml changes to be picked up. Click the Server view, then right-click WebSphere Commerce Test Server > Restart > Start.
  2. Switch to the Console view. If it is not already open, click Window > Show View > Other, expand Basic, and select Console. Click OK.
  3. When the server is started, review the Console output for any errors that may have resulted from the changes made.
  4. Open a standard browser and enter the following URL in the Address field:
    http://localhost/webapp/wcs/stores/servlet/ConsumerDirect/index.jsp
  5. The ConsumerDirect language selection page appears. Click United States English.
  6. The Top Categories page appears. Click ADVANCED SEARCH in the top header.
  7. The AdvancedSearchView page appears.
  8. Switch back to the Console view in Rational Application Developer, and inspect the output to see the User-Agent that has been detected. You may have to scroll up a few pages to get to the debug statements, or click the Advanced Search a second time to add the debug again. Depending on the browser used, the output looks similar to this:
    [11/24/08 13:10:04:500 EST] 00000036 SystemOut     
     O ===DEBUG=== User-Agent: Mozilla/5.0 
     (Windows; U; Windows NT 5.2; en-US; rv:1.8.1.18) 
     Gecko/20081029 Firefox/2.0.0.18
    [11/24/08 13:10:04:500 EST] 00000036 SystemOut     
     O ===DEBUG=== We will auto-detect the User-Agent 
    [11/24/08 13:10:04:500 EST] 00000036 SystemOut     
     O ===DEBUG=== User-Agent: Its Firefox!,set as Standard Browser
    [11/24/08 13:10:04:500 EST] 00000036 SystemOut     
     O ===DEBUG=== Setting to use BROWSER DEVICE

Correlate this to the MobileDeviceServletFilter class, which was made earlier to see where you have pulled the User-Agent from. Notice the above example was from Firefox, and being such, we have mapped it to the standard browser adapter.

Test the new servlet filter in a mobile device browser

You just inspected the User-Agent that was detected from a standard browser. Now you will test the filter by accessing the ConsumerDirect store in both your mobile device simulator and again inspect the console output to see the detected User-Agent.

  1. In IBM WebSphere Commerce Developer, switch to the Console view. If it is not already open, click Window > Show View > Other. Expand Basic and select Console. Click OK.
  2. Open the mobile device simulator by clicking the "Apple Safari" icon in the Quick Launch menu.
  3. In the mobile device simulator, enter the following URL in the Address field:
    http://localhost/webapp/wcs/stores/servlet/ConsumerDirect/index.jsp
  4. The ConsumerDirect language selection page appears. Click United States English.
  5. The Top Categories page appears. Click in the store window, hold and scroll to the right. Click ADVANCED SEARCH in the top header.
  6. The AdvancedSearchView page appears.
  7. Switch back to the Console view in Rational Application Developer, and inspect the output to see the User-Agent that has been detected. Depending on the browser used, the output looks similar to this:
    [11/24/08 13:08:52:703 EST] 00000038 SystemOut     
     O ===DEBUG=== User-Agent: Mozilla/5.0 
     (iPod; U; 
    CPU iPhone OS 2_1 like Mac OS X; en-us) AppleWebKit/525.18.1 
     (KHTML, like Gecko) Version/3.1.1 Mobile/5F137 Safari/525.20
    [11/24/08 13:08:52:703 EST] 00000038 SystemOut     
     O ===DEBUG=== We will auto-detect the User-Agent 
    [11/24/08 13:08:52:703 EST] 00000038 SystemOut     
     O ===DEBUG=== User-Agent: Its iPod, set as Mobile!
    [11/24/08 13:08:52:703 EST] 00000038 SystemOut     
     O ===DEBUG=== Setting to use MOBILE DEVICE

    Again, correlate this to the MobileDeviceServletFilter class, which was made earlier to see where you have pulled the User-Agent. Notice that the above example was from an Apple iPod, and being such, you have mapped it to the mobile device browser adapter.

    The output from the iPod simulator in Safrai looks similar to the following:

    [11/25/08 16:11:22:766 EST] 00000053 SystemOut     
     O ===DEBUG=== User-Agent: Mozilla/5.0 (Windows; U; 
     Windows NT 5.1; en-US) AppleWebKit/525.27.1 
    (KHTML, like Gecko) Version/3.2.1 Safari/525.27.1
    [11/25/08 16:11:22:766 EST] 00000053 SystemOut     
     O ===DEBUG=== We will auto-detect the User-Agent 
    [11/25/08 16:11:22:766 EST] 00000053 SystemOut     
     O ===DEBUG=== User-Agent: Its iPod Simulator (Safari), set as Mobile!
    [11/25/08 16:11:22:766 EST] 00000053 SystemOut     
     O ===DEBUG=== Setting to use MOBILE DEVICE

Implementing views for mobile devices

In the previous section, you created a servlet filter that detects the User-Agent header from a servlet request and sets the browser adapter accordingly. Now that you can differentiate between standard and mobile devices based on the User-Agent, you will implement some simple JSPs that are intended for display in a mobile device.

Create mobile version of header JSP fragments

As shown earlier, the AdvancedSearchView and CatalogSearchResultsView are not optimal for a mobile device because the display is much smaller and the bandwidth may be of concern. You will import a new simplified header for all views based on the out-of-the-box header. The simplified header reduces the page size and eliminates the navigator menu at the top of the page.

  1. From the J2EE perspective of Rational Application Developer, expand Stores > WebContent > ConsumerDirect > include > styles > style1.
  2. Right-click the style1 folder and click Import.
  3. In the Import wizard, select File system and click Next.
  4. Browse to change the source folder to MobileCommerceCode\Part4\4.2\include\styles\style1.
  5. Select the following JSP files to import them:
    • MobileCachedHeaderDisplay.jsp
    • MobileContentContainerTop.jsp
  6. Click Finish.
  7. Right-click ConsumerDirect > include and click Import.
  8. In the Import wizard, select File system and click Next.
  9. Browse to change the source folder to MobileCommerceCode\Part4\4.2\include\.
  10. Select the following files to import them:
    • MobileHeaderDisplay.jspf
    • MobileLayoutContainerTop.jspf
  11. Click Finish.

Create the mobile implementation of search

As shown earlier, the advanced search and search results are not optimal for a mobile device. The display is much smaller, links are smaller, and the bandwidth may be of concern. We will provide new simple implementations of the AdvancedSearchView and CatalogSearchResultsView to display better on the mobile device.

To implement these, you will import a new version of CatalogSearchForm.jsp called MobileCatalogSearchForm.jsp, and a new version of SearchResultDisplay.jsp called MobileSearchResultDisplay.jsp. Each is designed to be displayed on a mobile device:

  1. From the J2EE perspective of Rational Application Developer, expand Stores > WebContent > ConsumerDirect.
  2. Right-click ConsumerDirect folder and click New > Folder.
  3. Under the Folder Name, type mobile and click Finish.
  4. Right-click the newly created mobile directory and click Import.
  5. In the Import wizard, select File system and click Next.
  6. Browse and change the source folder to MobileCommerceCode\Part4\4.3\mobile.
  7. Select the following files to import them:
    • MobileCatalogSearchForm.jsp
    • MobileSearchResultDisplay.jsp
  8. Click Finish.

When viewing the modifications in later steps, notice the changes. The enhancements to the JSP follow some simple best practices. The overall page has been reduced in size to fit on the smaller browser. We have removed the images for each search result because they take up the display area and bandwidth to download. Also, we are using the shortDescription for each product, rather than longDescription, to reduce the text required to display.

Create mobile implementation of top category and product pages

Out-of-the-box top categories and product pages are not suitable for smaller display areas on the mobile devices. One of the best practices is to use the screen area to show maximum information without having to scroll. For example, in the top categories page, remove all the images to display the names of the top categories. We will provide new simple implementations of TopCategoriesDisplayView, CategoriesDisplayView, and ProductDisplayView to display better on the mobile device.

To implement these, you will import a new version of:

  • TopCategoriesDisplay.jsp called MobileTopCategoriesDisplay.jsp
  • CategoriesDisplay.jsp called MobileCategoriesDisplay.jsp
  • ProductDisplay.jsp
  • CachedProductOnlyDisplay.jsp called MobileProductDisplay.jsp, Mobile CachedProductOnlyDisplay.jsp

Each is designed to be displayed on a mobile device:

  1. From the J2EE perspective of Rational Application Developer, expand Stores > WebContent > ConsumerDirect > mobile.
  2. Right-click the newly created mobile directory from the previous section and click Import.
  3. In the Import wizard, select File system and click Next.
  4. Browse and change the source folder to MobileCommerceCode\Part4\4.4\mobile.
  5. Select the following files to import them:
    • MobileTopCategoriesDisplay.jsp
    • MobileCategoriesDisplay.jsp
    • MobileProductDisplay.jsp
    • MobileCachedProductOnlyDisplay.jsp
  6. Click Finish.

When viewing the modifications in later steps, notice the changes. The enhancements to the JSP follow best practices.

Create the new Struts configuration file for mobile devices

To keep the device-specific configurations separated, you will define a new Struts configuration file for these. You will use the same action-mapping and global-forward names as the out-of-the-box views, but define them for the specific browser adapter (or device format).

Note that you will use a device format ID of -2 in the Struts global-forwards. This corresponds to the "I Mode" device in the DEVICEFMT table in the WebSphere Commerce database. Alternatively, you can define a new DEVICEFMT and use it for different devices.

  1. From the J2EE perspective of IBM WebSphere Commerce Developer, expand Stores > Struts.
  2. Right-click Struts and click New > Other.
  3. In the Wizard, expand Web > Struts > Struts Configuration File > Next.
  4. On the Struts Configuration File Wizard, enter the following:
    • Folder: /Stores/WebContent/WEB-INF
    • File name: struts-config-mobile.xml
  5. Click Finish. The struts-config-mobile.xml source view opens for editing. If not, from the J2EE perspective of Rational Application Developer, expand Stores > Web Content > WEB-INF and double-click struts-config-mobile.xml.
  6. Define a new global-forward and action for the AdvancedSearchView specific to storeID = 10001 and deviceFormatID = -2. Insert the following section into the <global-forwards> section of the struts-config-mobile.xml file:
    <!-- Global Forwards -->
    <global-forwards>	
    	<forward className="com.ibm.commerce.struts.ECActionForward" 
    	 name="AdvancedSearchView/10001/-2" 				
    	 path="/mobile/MobileCatalogSearchForm.jsp"/>
    	<forward className="com.ibm.commerce.struts.ECActionForward" 
    	 name="CatalogSearchResultView/10001/-2" 			
    	 path="/mobile/MobileSearchResultDisplay.jsp"/>
    </global-forwards>

    These global-forwards are using the same forward names as the default configurations, but you added "/-2" to indicate this applies to device format -2 (I Mode), and you have put in custom JSP pages for the path of each forward. Now only on device format -2 will these global-forwards be used. Otherwise, the runtime framework will use the default configuration (where no device format is specified).

  7. Define a new action for the AdvancedSearchView specific to storeID = 10001. Insert the following section into the <action-mappings> section of the struts-config-mobile.xml file:
    <!-- Action Mappings -->
    <action-mappings type="com.ibm.commerce.struts.ECActionMapping">
    	<action path="/AdvancedSearchView" 
    	 type="com.ibm.commerce.struts.BaseAction">
    	 <set-property property="https" value="10001:0"/>
    	</action>
    	<action path="/CatalogSearchResultView" 
    	 type="com.ibm.commerce.struts.BaseAction">
    	 <set-property property="https" value="10001:0"/>
    	</action>
    </action-mappings>
  8. Repeat Steps 6 and 7 for TopCategoriesDisplayView, CategoriesDisplayView, and ProductDisplayView:
    <forward className="com.ibm.commerce.struts.ECActionForward" 
           name="TopCategoriesDisplayView/10001/-2" 
           path="/mobile/MobileTopCategoriesDisplay.jsp"/>
    	<forward className="com.ibm.commerce.struts.ECActionForward" 
           name="ProductDisplayView/10001/-2" 
           path="/mobile/MobileProductDisplay.jsp"/>
    	<forward className="com.ibm.commerce.struts.ECActionForward" 
           name="ProductDisplayView/10001/-2" 
           path="/mobile/MobileCategoriesDisplay.jsp"/>
    
    
    	<action path="/TopCategoriesDisplayView" 
    	   type="com.ibm.commerce.struts.BaseAction">
    	   <set-property property="https" value="10001:0"/>
    	</action>
    	<action path="/ProductDisplayView" 
    	  type="com.ibm.commerce.struts.BaseAction">
    	  <set-property property="https" value="10001:0"/>
    	   </action>
    	<action path="/CategoryDisplayView" 
          type="com.ibm.commerce.struts.BaseAction">
    	  <set-property property="https" value="10001:0"/>
    	   </action>
  9. Note you can find the completed file under MobileCommerceCode\Part4\4.5\struts-config-mobile.xml. Compare it to your implementation.
  10. Save and close the modified struts-config-mobile.xml.

Register new CategoryDisplayView and ProductDisplayView JSPs

Insert the following records into the WebSphere Commerce database:

insert into DISPENTREL values (0, 50001, null, -2, 10001, 
 'mobile/MobileProductDisplay.jsp', 'ProductBean',0,0,null, null,-1,null,null,0)
insert into DISPCGPREL values (0, 50001, null, -2, 'mobile/MobileCategoriesDisplay.jsp',
 10001,0,null,-1,null,null,null,0)

Ensure that the value 50001 for DISPENTREL_ID and DISPCGPREL_ID is unique in the tables.

Register the new Struts configuration in the Stores project

You have now defined mobile device-specific global-forwards and action-mappings in a new Struts configuration file. You now need to include this struts-config-mobile.xml as one of the Struts configurations for the WebSphere Commerce Stores Request Servlet to use. To do this, follow these steps:

  1. From the J2EE perspective of Rational Application Developer, expand Stores, and double-click Deployment Descriptor: Stores to open for editing.
  2. When the Web Deployment Descriptor opens, click the Source tab to modify web.xml.
  3. Locate the following section in the source XML:
    <param-value>/WEB-INF/struts-config.xml,/WEB-INF/struts-config-GiftCenter.xml,/
     WEB-INF/struts-config-migrate.xml,/WEB-INF/struts-config-ext.xml</param-value>
  4. Add in the struts-config-mobile.xml to this list. You will put the new XML as the last entry, so it takes precedence over all other Struts configuration files for this Web module during runtime.

    Click to see code listing

    <param-value>/WEB-INF/struts-config.xml,/WEB-INF/struts-config-GiftCenter.xml,/
     WEB-INF/struts-config-migrate.xml,/WEB-INF/struts-config-ext.xml,/WEB-INF/ struts-config-mobile.xml</param-value>
  5. Note you can find the completed file under MobileCommerceCode\Part4\4.6\web.xml. Compare it to your implementation.
  6. Save the changes and close the Web Deployment Descriptor.

Test the new mobile views in simulator

At this point, you have made a new servlet filter, which detects the User-Agent from the HTTP Header and sets the corresponding browser adapter to identify which global-forwards from Struts will be used. You are now ready to test the new configuration to see the new simplified mobile JSP pages when you view the Advanced Catalog Search in ConsumerDirect.

  1. Re-start the WebSphere Commerce Test Server to ensure the modified configuration files are used.
  2. Open the mobile device simulator by clicking the "Apple Safari" icon in the Quick Launch menu.
  3. In the mobile device simulator, enter the following URL in the Address field:
http://localhost/webapp/wcs/stores/servlet/ConsumerDirect/index.jsp
  1. The ConsumerDirect language selection page appears. Click United States English.
  2. The new Mobile Top Categories page appears. Notice the changes to the display (Figure 7).
    Figure 7. ConsumerDirect modified TopCategoriesDisplay in a mobile device simulator
    ConsumerDirect modified TopCategoriesDisplay in a mobile device simulator
  3. Click in the store window, hold, and scroll to the right. Click MOBILE SEARCH in the top header.
  4. The new mobile AdvancedSearchView page appears (Figure 8). This reflects the new implementation you just created in the previous steps, specific to the mobile device.
    Figure 8. ConsumerDirect modified AdvancedSearch in a mobile device simulator
    ConsumerDirect modified AdvancedSearch in a mobile device simulator
  5. Enter a search criteria of "chair" in the "Search for" text box and click the SEARCH button. This takes you to the new Mobile CatalogSearchResultView. Again, notice the new simplified implementation for the mobile device (Figure 9).
    Figure 9. ConsumerDirect modified CatalogSearchResultDisplay in a mobile device simulator
    ConsumerDirect modified CatalogSearchResultDisplay in a mobile device simulator
  6. To compare, open a standard browser and repeat the sections above to ensure the original behavior has not changed for a non-mobile device.
  7. Also inspect the console output in Rational Application Developer to see the User-Agent and browser adapters, which are detected and mapped.

Caching the configuration for mobile WebSphere Commerce

You now have view implementations specific to a mobile device browser and a standard browser. In this section, you will explore the caching considerations involved with these new implementations. First, you will explore the behavior of using a standard way of caching the TopCategoriesDisplay, highlighting the problems encountered. Then you will see how to cache based on the device from the command context.

Cache the TopCategoriesDisplay

First, you will add a cache-entry for the TopCategoriesDisplay using the common approach of servlet caching, along with typical components as part of the cache-id. At the end of this section, you will see that this introduces a problem when using the same Struts action-mapping (for example, TopCategoriesDisplay) for multiple global-forwards, which is differentiated based on device format.

  1. From the J2EE perspective of Rational Application Developer, expand Stores > WebContent > WEB-INF.
  2. Double-click cachespec.xml to open it for editing.
  3. Between the <cache> and </cache> tags, insert the following cache-entry into the cachespec.xml:
    	<cache-entry>
    		<class>servlet</class>
    		<name>com.ibm.commerce.struts.ECActionServlet.class</name>
    		<property name="consume-subfragments">true</property>
    		<property name="save-attributes">
    			false
    			<exclude>jspStoreDir</exclude>
    		</property>
    		<!-- TopCategoriesDisplay?langId=-1&storeId=10001&catalogId=10001 -->
    		<cache-id>
    			<component id="" type="pathinfo">
    				<required>true</required>
    				<value>/TopCategoriesDisplay</value>
    			</component>
    			<component id="storeId" type="parameter">
    				<required>true</required>
    			</component>
    			<component id="catalogId" type="parameter">
    				<required>true</required>
    			</component>
    			<component id="langId" type="parameter">
    				<required>true</required>
    			</component>
    		</cache-id>
    	</cache-entry>
  4. Note that an updated cachespec.xml is also available under MobileCommerceCode\Part5\5.2\cachespec.xml for you to compare the modifications.
  5. Save the changes, but leave the cachespec.xml open for further changes.

Test the cached TopCategoriesDisplay in both browsers

Now that you are caching the TopCategoriesDisplay, you will access this page in a standard browser first and then open it in the mobile device simulator.

  1. Open a standard Web browser and enter the following URL in the Address field:
    http://localhost/webapp/wcs/stores/servlet/ConsumerDirect/index.jsp
  2. The ConsumerDirect language selection page appears. Click United States English.
  3. The TopCategoriesDisplay appears.
  4. In a separate browser, access the Dynamic Cache Monitor via the following URL:
    http://localhost/cachemonitor
  5. In the Cache Monitor, click Cache Contents in the left navigation menu.
  6. Search for "Template" in /webapp/wcs/stores/com.ibm.commerce.struts.ECActionServlet.class.
  7. Scroll to the right and observe the stored cache ID, which looks similar to the following:
    /webapp/wcs/stores/com.ibm.commerce.struts.ECActionServlet.class:
     pathinfo=/TopCategoriesDisplay:storeId=10001:catalogId=10001:
     langId=-1:UTF-8:requestType=GET

    Notice this corresponds to the cache-id and cache-entry you just placed in cachespec.xml.

  8. Open the mobile device simulator by clicking the "Apple Safari" icon in the Quick Launch menu.
  9. In the simulator, enter the following URL in the Address field:
    http://localhost/webapp/wcs/stores/servlet/ConsumerDirect/index.jsp
  10. The ConsumerDirect language selection page appears. Click United States English.
  11. The TopCategoriesDisplay appears.
  12. Notice that the view displayed does not look like the mobile implementation any more, but looks like the standard browser implementation.
  13. To understand why, again refer back to the browser that has the Dynamic Cache Monitor open.
  14. In the Cache Monitor, click Cache Contents in the left navigation menu.
  15. Search for "Template" in /webapp/wcs/stores/com.ibm.commerce.struts.ECActionServlet.class.
  16. Scroll to the right and observe the stored Cache ID, which looks similar to the following:
    /webapp/wcs/stores/com.ibm.commerce.struts.ECActionServlet.class:
     pathinfo=/TopCategoriesDisplay:storeId=10001:catalogId=10001:
     langId=-1:UTF-8:requestType=GET

This is the same entry as before. It was retrieved as a cache-hit during the second request, which came from the mobile device simulator after caching on the first request from the standard browser.

You then see a problem where the second device displays the view in the same format as the first device. The reason is that you are using the same action-mapping (TopCategoriesDisplay, in this case) for two different JSPs referenced by the global-forwards. Remember, you defined one global-forward for each device type.

Cache the entry based on DeviceFormatId

Based on this, a new cache-id component is introduced to differentiate cached pages based on the device format, if you are using the same action-mapping.

  1. From the J2EE perspective of Rational Application Developer, expand Stores > WebContent > WEB-INF.
  2. Double-click cachespec.xml to open it for editing, if not already open.
  3. Locate this section:
    		<component id="langId" type="parameter">
    			<required>true</required>
    		</component>
    	</cache-id>
  4. In between the </component> and </cache-id> tags, insert the following new component for this cache-id. You can also find this snippet in MobileCommerceCode\Part5\5.4\snippet.xml:
    	<!-- base entry on device type -->
    	<component id="CommandContext" type="attribute">
    		<required>true</required>
    		<method>
    			getDeviceFormatId
    		</method>
    	</component>

    Note that you are retrieving the DeviceFormatId from the CommandContext object and adding this as a required component for the cache-id. This ensures that you are caching based on the specific device format to avoid the issue that was demonstrated in the previous section.

  5. For reference, an updated version of the cachespec.xml is in MobileCommerceCode\Part5\5.3\cachespec.xml.
  6. Save the changes and close the cachespec.xml.

Test the device-specific caching of TopCategoriesDisplay

Now that you have an updated caching policy to cache the TopCategoriesDisplay per the device format, you will repeat the test to see if you get two separate cache entries in the Dynamic Cache Monitor and to see the different device format IDs as part of the cache-id for each.

  1. From the Dynamic Cache Monitor, clear the cache by clicking Cache Contents, then the Clear Cache button.
  2. Repeat section Test the cached TopCategoriesDisplay in both browsers to test the cached TopCategoriesDisplay in the standard browser and the mobile device simulator.

Note that the views are displayed as expected, rather than getting the same display for both devices. In the Cache Contents of the Cache Monitor this time, observe that there are two different cache IDs for the template /webapp/wcs/stores/com.ibm.commerce.struts.ECActionServlet.class.

The two Cache IDs look similar to the following:

/webapp/wcs/stores/com.ibm.commerce.struts.ECActionServlet.class:
 pathinfo=/TopCategoriesDisplay:storeId=10001:catalogId=10001:
 langId=-1:CommandContext:-1:UTF-8:requestType=GET
/webapp/wcs/stores/com.ibm.commerce.struts.ECActionServlet.class:            
 pathinfo=/TopCategoriesDisplay:storeId=10001:catalogId=10001:
 langId=-1:CommandContext:-2:UTF-8:requestType=GET

Notice the CommandContext component within each cache ID. This reflects the caching specific to the getDeviceFormatId value from the CommandContext you added, referencing the standard device (CommandContext:-1) and mobile device (CommandContext:-2).


Allowing the user to select device preference

At this point in the tutorial, you have implemented a servlet filter that intercepts a request to the Stores Request servlet and determines the User-Agent from the HTTP Header. Based on this User-Agent, the requested is mapped to a specific browser adapter automatically. However, some mobile devices that allow zooming and scrolling can still handle the fully functional display. An online shopper may want to view this standard display, rather than the simplified mobile-specific view.

This optional section of the tutorial introduces one such way to achieve this behavior. You will create a link in the header of both the standard and the mobile sites, which will allow the user to force a switch between the two. This overrides the device preference, which you automatically assign based on the User-Agent. You will do this with the use of a cookie, storing the preferred device format.

Create a link in the header on the mobile site to allow the user to force a switch to the standard display.

  1. From the J2EE perspective of Rational Application Developer, expand Stores > WebContent > ConsumerDirect > include > styles > style1.
  2. Double-click MobileCachedHeaderDisplay.jsp. Click the Source tab if not already selected.
  3. Scroll down to the end of the file and locate the following section:
    	   </tbody>
    	</table>
    	
    	<!--END HEADER-->
    	<!-- End - JSP File name:  style1/CachedHeaderDisplay.jsp -->
  4. Directly above the </tbody> tag , insert the following code snippet. This snippet is also found in MobileCommerceCode\Part6\6.2\snippet1.txt:
    <!-- use standard browser instead of mobile -->
    <tr>
     <td class="m_top" id="WC_CachedHeaderDisplay_TableCell_46">
      <font color="red"><b>
       ***<a href="<c:out value="${GoStandardURL}"/>" class="m_top_link">
       Switch to Standard Browser View!</a></b>***
      </font>
     </td>
    </tr>
  5. Create the URL that you will return to, in this case, you will go to the search page. Locate the following section:
    <c:url var="AdvancedSearchViewURL" value="AdvancedSearchView">
    	<c:param name="langId" value="${langId}" />
    	<c:param name="storeId" value="${WCParam.storeId}" />
    	<c:param name="catalogId" value="${catalogId}" />
    </c:url>
  6. Directly below the </c:url> above, insert the following code snippet. This snippet is also found in MobileCommerceCode\Part6\6.3\snippet2.txt:
    <c:url var="GoStandardURL" value="TopCategoriesDisplay">
    	<c:param name="langId" value="${langId}" />
    	<c:param name="storeId" value="${WCParam.storeId}" />
    	<c:param name="catalogId" value="${catalogId}" />
    	<c:param name="devicePref" value="BROWSER" />
    </c:url>
  7. Note a complete version of the MobileCachedHeaderDisplay.jsp after this change is found in MobileCommerceCode\Part6\6.2\MobileCachedHeaderDisplay.jsp to compare to your revised version.
  8. Save the changes and close the file.

Note that this link sets the devicePref=BROWSER so that while viewing a mobile display. You will force it to switch over to the standard browser display.

Next, you will do the same steps, but create the link in the standard header to allow the user to force a switch to the mobile display.

  1. From the J2EE perspective of Rational Application Developer, expand Stores > WebContent > ConsumerDirect > include > styles > style1.
  2. Double-click CachedHeaderDisplay.jsp.
  3. Scroll down to the end of the file and locate the following section:
    	</tr></tbody>
    	</table>
    	
    	<!--END HEADER-->
    	<!-- End - JSP File name:  style1/CachedHeaderDisplay.jsp -->
  4. Directly between the </tr> and the </tbody> tags, insert the following code snippet. This snippet is also found in MobileCommerceCode\Part6\6.3\snippet1.txt:
    <!-- use standard browser instead of mobile -->
     <tr>
      <td class="m_top" id="WC_CachedHeaderDisplay_TableCell_46">
       <font color="red"><b>
    	***<a href="<c:out value="${GoMobileURL}"/>" class="m_top_link">
    	Switch to Mobile Browser View!</a></b>***
       </font>
      </td>
    </tr>
  5. Create the URL that you will return to. In this case, you will go to the search page. Locate the following section:
    	<c:url var="AdvancedSearchViewURL" value="AdvancedSearchView">
    		<c:param name="langId" value="${langId}" />
    		<c:param name="storeId" value="${WCParam.storeId}" />
    		<c:param name="catalogId" value="${catalogId}" />
    	</c:url>
  6. Directly below the </c:url> above, insert the following code snippet. This snippet is also found in MobileCommerceCode\Part6\6.3\snippet2.txt:
    	<c:url var="GoMobileURL" value="TopCategoriesDisplay">
    		<c:param name="langId" value="${langId}" />
    		<c:param name="storeId" value="${WCParam.storeId}" />
    		<c:param name="catalogId" value="${catalogId}" />
    		<c:param name="devicePref" value="MOBILE" />
    	</c:url>
  7. Note a complete version of the CachedHeaderDisplay.jsp after this change is found in MobileCommerceCode\Part6\6.3\CachedHeaderDisplay.jsp to compare to your revised version.
  8. Save the changes and close the file.
  9. In Windows Explorer, remove the compiled JSP files to force the parent files to get recompiled after our header changes:
    <WCToolkit>\wasprofile\temp\localhost\server1\WC\Stores.war\ConsumerDirect

Note that this link sets the devicePref=MOBILE so that while viewing a mobile display, you will force it to switch over to the standard browser display.

Modify the servlet filter to set preferred display

To switch to the mobile display (from standard) or the standard display (from mobile), create a link in the header so it is available from all pages. This link submits the current view adding a parameter called devicePref and sets to either BROWSER or MOBILE, depending on which display is the one to be switched to.

Currently, the MobileDeviceServletFilter automatically detects the User-agent from the header of the servlet request and maps that to the browser adapter.

The updated behavior of the filter is as follows:

  1. Check the serlvet request parameters for a parameter called "devicePref". If this was set, it was because the user has clicked the link on the store to switch the display from mobile to standard (or vice-versa).
  2. If the parameter is set, you create/update the cookie called DEVICEPREF and set the value of this parameter. You also set the browser adapter for the current request to match that of the parameter.
  3. If the parameter is not set, check if a cookie already exists called DEVICEPREF. This means that the display preference link was clicked in a prior request of this session, but you will keep that preference for this request as well. Set the browser adapter for the current request to match that of the cookie.
  4. If the parameter is not set, and the cookie does not already exist, use the default behavior implemented and automatically assign the browser adapter based on the User-Agent in the request header.

To implement this logic, follow the steps below:

  1. From the J2EE perspective of Rational Application Developer, expand WebSphereCommerceServerExtensionsLogic > src > com.wstc.filter.
  2. Double-click MobileDeviceServletFilter.java to open the file for editing.
  3. Locate the following section:
    	//Wrap the response and request objects so we can play with the
    	// cookies
    	HttpServletResponseWrapper resp = new HttpServletResponseWrapper(
    		(HttpServletResponse) response);
    	HttpServletRequestWrapper req = new HttpServletRequestWrapper(
    		(HttpServletRequest) request);
  4. Directly below the print statement above, insert the following code snippet. This snippet is also found in MobileCommerceCode\Part6\6.4\snippet1.txt:
    String devicePref = (String) serRequest.getParameter("devicePref");
    	
     if (devicePref != null) {
    	System.out
    	.println("===DEBUG=== Adding cookie to response based on devicePref in request "
    						+ devicePref);
    	//then set cookie to say mobile
    	resp.addCookie(new javax.servlet.http.Cookie("DEVICEPREF",
    	 devicePref));
    	} else {
    	 System.out
    	 .println("===DEBUG=== devicePref is null in request , 
    	  no cookie added");
    	}
    	
    	// lets check cookies, and set our devicePref to this
    	Cookie[] cookie = req.getCookies();
    	if (cookie != null && cookie.length > 0) {
    	 for (int i = 0; i < cookie.length; i++) {
    	  Cookie currentCookie = cookie[i];
    	  String cookieName = currentCookie.getName();
    	  System.out.println("===DEBUG=== COOKIE = " + cookieName);
    	  if (cookieName.equals("DEVICEPREF")) {
    		device = new String(currentCookie.getValue());
    		System.out.println("===DEBUG=== DEVICEPREF COOKIE = "
    	     + device);
    			}
    		}
    	}
  5. Inspect the code above. Get the request parameter "devicePref", which is what you have set on the links just created in the headers to force to a different display. If this parameter is set, create a cookie called "DEVICEPREF" in the response with the same value as the parameter.

    Finally, if the parameter was not set, iterate through all the cookies in the request and check if you already have a DEVICEPREF cookie set (from a previous request). If so, set this to the current device.

  6. Locate the following section:
          //The current User-Agent we detect from the HTTP Header
    	System.out.println("===DEBUG=== User-Agent: " + header);
  7. Directly below the print statement above, insert the following code snippet. This snippet is also found in MobileCommerceCode\Part6\6.4\snippet2.txt:
    	// If devicePref set in this request, lets use that
    	if (devicePref != null) {
    	 device = new String(devicePref);
    	 System.out.println("===DEBUG=== devicePref is not null: "
    	  + devicePref);
    	}
  8. Inspect the code above. The important line here is where you are setting the device to the value of the devicePref request parameter.
  9. Note that a modified version of the MobileDeviceServletFilter.java is available in MobileCommerceCode\Part6\6.4\snippet2.txt.
  10. Save the changes to MobileDeviceServletFilter.java.

Now that you have modified the JSP to include a link to switch from between the standard and mobile views, you will test the logic in the mobile device simulator and try to force the standard display in the mobile browser.

  1. Re-start the WebSphere Commerce Test Server to ensure the modified configuration files are used.
  2. From the Dynamic Cache Monitor, clear the cache by clicking Cache Contents, then the Clear Cache button.
  3. Open the mobile device simulator by clicking the "Apple Safari" icon in the Quick Launch menu.
  4. In the simulator, enter the following URL in the Address field:
    http://localhost/webapp/wcs/stores/servlet/ConsumerDirect/index.jsp
  5. The ConsumerDirect language selection page appears. Click United States English.
  6. The mobile version of TopCategoriesDisplay appears. Notice the new link *** Switch to Standard Browser View! *** (Figure 10).
    Figure 10. TopCategoriesDisplay in a mobile device simulator with link to force a standard display
    TopCategoriesDisplay in a mobile device simulator with link to force a standard display
  7. Click the *** Switch to Standard Browser View! *** link under the header. This reloads the page in the standard browser display instead of the mobile display.
  8. Notice the debug output in the Rational Application Developer console, which looks similar to the following:
    	[11/26/08 10:11:20:719 EST] 00000061 SystemOut     
    	 O ===DEBUG=== Adding cookie to response based on devicePref 
    	 in request BROWSER
    	[11/26/08 10:11:20:719 EST] 00000061 SystemOut     
    	 O ===DEBUG=== COOKIE = JSESSIONID
    	[11/26/08 10:11:20:719 EST] 00000061 SystemOut     
    	 O ===DEBUG=== COOKIE = WC_SESSION_ESTABLISHED
    	[11/26/08 10:11:20:719 EST] 00000061 SystemOut     
    	 O ===DEBUG=== COOKIE = WC_ACTIVEPOINTER
    	[11/26/08 10:11:20:719 EST] 00000061 SystemOut     
    	 O ===DEBUG=== COOKIE = WC_GENERIC_ACTIVITYDATA
    	[11/26/08 10:11:20:719 EST] 00000061 SystemOut     
    	 O ===DEBUG=== COOKIE = WC_USERACTIVITY_-1002
    	[11/26/08 10:11:20:719 EST] 00000061 SystemOut     
    	 O ===DEBUG=== User-Agent: Mozilla/5.0 (Windows; U; 
    	 Windows NT 5.1; en-US) AppleWebKit/525.27.1 (KHTML, 
    	 like Gecko) Version/3.2.1 Safari/525.27.1
    	[11/26/08 10:11:20:719 EST] 00000061 SystemOut     
    	 O ===DEBUG=== devicePref is not null: BROWSER
    	[11/26/08 10:11:20:719 EST] 00000061 SystemOut     
    	 O ===DEBUG=== Setting to use BROWSER DEVICE

    Notice that you find devicePref in the request parameters, and then create a cookie into our response. The devicePref was set to BROWSER (as in standard browser) and was set from the URL you just clicked.

  9. Click the Advanced Search link and notice that any subsequent requests you now detect the DEVICEPREF cookie in the request to keep using the standard browser on a mobile device:
    	[11/26/08 10:07:49:438 EST] 00000037 SystemOut     
    	 O ===DEBUG=== devicePref is null in request , no cookie added
    	[11/26/08 10:07:49:438 EST] 00000037 SystemOut     
    	 O ===DEBUG=== COOKIE = DEVICEPREF
    	[11/26/08 10:07:49:438 EST] 00000037 SystemOut     
    	 O ===DEBUG=== DEVICEPREF COOKIE = BROWSER
    	[11/26/08 10:07:49:438 EST] 00000037 SystemOut     
    	 O ===DEBUG=== COOKIE = JSESSIONID
    	[11/26/08 10:07:49:438 EST] 00000037 SystemOut     
    	 O ===DEBUG=== COOKIE = WC_SESSION_ESTABLISHED
    	[11/26/08 10:07:49:438 EST] 00000037 SystemOut     
    	 O ===DEBUG=== COOKIE = WC_ACTIVEPOINTER
    	[11/26/08 10:07:49:438 EST] 00000037 SystemOut     
    	 O ===DEBUG=== COOKIE = WC_GENERIC_ACTIVITYDATA
    	[11/26/08 10:07:49:438 EST] 00000037 SystemOut     
    	 O ===DEBUG=== COOKIE = WC_USERACTIVITY_-1002
    	[11/26/08 10:07:49:438 EST] 00000037 SystemOut     
    	 O ===DEBUG=== User-Agent: Mozilla/5.0 (Windows; U; 
    	 Windows NT 5.1; en-US) AppleWebKit/525.27.1 (KHTML, 
    	 like Gecko) Version/3.2.1 Safari/525.27.1
    	[11/26/08 10:07:49:438 EST] 00000037 SystemOut     
    	 O ===DEBUG=== Setting to use BROWSER DEVICE
  10. Click the *** Switch to Mobile Browser View! *** link to switch back to the mobile display. Continue to explore the switching between the mobile and standard views.

Conclusion

You have now seen how to tailor a WebSphere Commerce store for a mobile device. Using a servlet filter to map to different Struts action mappings, you learned to target specific displays to specific devices, without too much development on the existing site. You have also explored some enhancements, such as allowing the user to force the display type (mobile or standard) and some key caching considerations.


Download

DescriptionNameSize
Code sample filesMobileCommerceCode.zip50 KB

Resources

Comments

developerWorks: Sign in

Required fields are indicated with an asterisk (*).


Need an IBM ID?
Forgot your IBM ID?


Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. Information in your profile (your name, country/region, and company name) is displayed to the public and will accompany any content you post, unless you opt to hide your company name. You may update your IBM account at any time.

All information submitted is secure.

Choose your display name



The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

Required fields are indicated with an asterisk (*).

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.

 


All information submitted is secure.

Dig deeper into WebSphere on developerWorks


static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=WebSphere
ArticleID=392975
ArticleTitle=Implementing mobile WebSphere Commerce
publish-date=06032009