Skip to main content

skip to main content

developerWorks  >  WebSphere  >

Implementing mobile WebSphere Commerce

developerWorks
Go to the previous pagePage 3 of 11 Go to the next page

Document options
PDF format - Fits A4 and Letter

PDF - Fits A4 and Letter
1259 KB (49 pages)

Get Adobe® Reader®

Sample code


My developerWorks needs you!

Connect to your technical community


Rate this tutorial

Help us improve this content


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.



Back to top


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.


Back to top


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.


Back to top


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.



Back to top


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
    



Back to top



Go to the previous pagePage 3 of 11 Go to the next page