ZOFTINO.COM android and web dev tutorials

Mobile and Desktop Sites Using Spring Mobile

Displaying content based on device screen size helps improve readability of any web page. With responsive design page content can be displayed based on screen size using @media rules in CSS. If you have requirement to display content only in two formats one for desktop screens and other one for mobile and table screens, you can create two versions of pages for desktop and small screens. The only drawback with this approach is you need to maintain two versions of pages. If there is a change in a page, you need to do it in two versions of the page. But you don’t need to worry about @media rules and you can provide screen specific design with freedom meaning it allows to provide completely different design for different screens.

I am going to show how to render two versions of a page using Spring mobile. Spring mobile detects type of device requesting a page and renders either desktop versions or mobile version of the page based on the type of device.

Below is the spring configuration for view resolver. DeviceResolverHandlerInterceptor determines the device type using request information. LiteDeviceDelegatingViewResolver renders appropriate view for the target device. All jsp files under WEB-INF/jsp/ are rendered for desktop screen. All views under WEB-INF/jsp/mobile/ are rendered for mobile and tablets. View names are common meaning jsp file names should be same for both versions. No extra steps are required in Controller. Controller just returns view name as usual and view resolvers picks appropriate version based on device type.

      <bean class="org.springframework.mobile.device.site.SitePreferenceWebArgumentResolver" />           
	<bean id="sitePrefRepCust" class="org.springframework.mobile.device.site.CookieSitePreferenceRepository">        
        <property name="cookieName" value="devicepref"></property>    
    <bean id="sitePrefhandCust" class="org.springframework.mobile.device.site.StandardSitePreferenceHandler ">        
       <constructor-arg ref="sitePrefRepCust"/>  
        <bean class="org.springframework.mobile.device.DeviceResolverHandlerInterceptor" />
        <bean class="org.springframework.mobile.device.site.SitePreferenceHandlerInterceptor">
        	<constructor-arg ref="sitePrefhandCust"/>
    <bean id="liteDeviceAwareViewResolver" class="org.springframework.mobile.device.view.LiteDeviceDelegatingViewResolver">
         <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
       		 <property name="prefix" value="/WEB-INF/jsp/"></property>
        	 <property name="suffix" value=".jsp"></property>  
        <property name="mobilePrefix" value="mobile/"></property>
        <property name="tabletPrefix" value="mobile/"></property>