Monday, December 6, 2010

Create Mobile Decorator with Sitemesh and jQuery Mobile

In my previous post,Mobilize Your Java Web Application, I mentioned to provide a separate decorator for mobile user. In this post I will demonstrate how to achieve this:

1. automatically apply mobile decorator if the request came from mobile browser

2. leave it to user, if user choose the mobile version in their request parameter, such as "document/list?version=mobile".




First of all, let me show you the mobile decorator I developed using jQuery Mobile:



<!DOCTYPE html>
<html>
   <head>
   <meta charset="utf-8" />
   <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
   
   <decorator:title default="${title}" /> 
   
    <link rel="apple-touch-icon" href="img/myTouchIcon.png" />
    <link rel="stylesheet" href="http://code.jquery.com/mobile/1.0a2/jquery.mobile-1.0a2.min.css" />
 <script type="text/javascript" src="<c:url value='/scripts/jquery-1.4.4.min.js'/>"></script>
    <script src="http://code.jquery.com/jquery-1.4.4.min.js"></script>
 <script src="http://code.jquery.com/mobile/1.0a2/jquery.mobile-1.0a2.min.js"></script>
 </head>
<body>
 <div data-role="page">

   <header data-role="header">
  <h1>
    <img alt="logo" src="<c:url value='/images/logo.png'/>"></img>
  </h1>
   </header>

   <div data-role="content">
   <decorator:body />
   </div>

   <footer data-role="footer">
 <h4> www.ke-cai.net.com </h4>
   </footer>

 </div>

</body>
</html>

Create a sitemesh.xml and put it in "WEB-INF" folder, we're going to add two decorator mapping.

1.Mobile AgentDecoratorMapper

In Sitemesh, there is a AgentDecoratorMapper which will select decorator by user's agent string.
<mapper class="com.opensymphony.module.sitemesh.mapper.AgentDecoratorMapper">
   <param name="match.iPhone" value="mobile" />
   <param name="match.Android" value="mobile" />
   <param name="match.webos" value="mobile" />
   <param name="match.palm" value="mobile" />
   <param name="match.blackberry" value="mobile" />
   <param name="match.opera mini" value="mobile" />
  </mapper>

AgentDecoratorMapper will check user's agent string, if it contains "iphone","andorid" or others in our configuration, it will try to find the decorator end with "-mobile.jsp".

2. Mobile Version ParameterDecoratorMapper

<mapper
   class="com.opensymphony.module.sitemesh.mapper.ParameterDecoratorMapper">
   <param name="decorator.parameter" value="version" />   
  </mapper>

We have to config another decorator in decorators.xml for this mapping:
<decorators defaultdir="/WEB-INF/decorators">
 <excludes>
  <pattern>/resources/*</pattern>
  <pattern>/file/upload**</pattern>
 </excludes>

 <decorator name="default" page="default.jsp">
  <pattern>**</pattern>
 </decorator>
 
 <decorator name="mobile" page="default-mobile.jsp">
 </decorator>

</decorators>

Now your mobile decorator will apply to request with parameter"?version=mobile".

0 comments: