grails mobile device detection using spring mobile and adding different views for mobile and web



grails mobile device detection using spring mobile and adding different views for mobile and web
Recently i worked on a project that has to generate different views for mobile and tab and web. we can design website as responsive but i have different designs for mobile and web and tablet. so i went through spring mobile plugin for grails. The plugin adds dynamic methods to your controllers to determine what type of client is accessing the app:
isMobile() will be true if the client is a mobile phone.
isTablet() will be true if the client is a tablet.
isNormal() will be true if the client is not a mobile phone or tablet.
Additionally, you can run code conditionally, with access to the current org.springframework.mobile.device.Device instance, with this method:
withMobileDevice(Closure closure)
def list() {
   def view = "list"
   withMobileDevice { device ->
      view = "mobileList"
   }
   render(view: view, model: [list: listInstance])
}
But we don't have withTabletDevice closure to generate views for tablets device.
for small application it is okay to use this closure to generate views. What about if we have many controllers with many actions?
Here is the way to implement single place to handle device specific views.

1. Install grails spring mobile plugin
2. Create A BaseController
class BaseController {

 String prefix = "/web";
 
 def beforeInterceptor = {
  if(isMobile()){
   prefix = "/mobile"
  } else if(isTablet()){
   prefix = "/tablet"
  }
 }
 
 def afterInterceptor = { model, modelAndView ->
  if(modelAndView) {
   modelAndView.viewName = prefix + modelAndView.viewName
  }
 }
}
beforeInterceptor : Allows the interception of an action before it is executed. A beforeInterceptor can optionally halt execution of the action.

afterInterceptor : Allows interception of actions after they have executed, but before the view is rendered.

3.Extend the basecontroller
class UserController extends BaseController{

       def list() {
       render(view: view, model: [list: listInstance])
   }
}
4.create device specific views under views folder
   views
       -> mobile
           ->mobileviews
       -> tablet
           ->tabletviews
       -> web
           ->webviews
Thats it. Now check your application in different devices

Categories: