7.4. MobileESP
MobileESP is an API detects if a user is accessing a website from a mobile device. This results in loading mobile versions of webpages as opposed to loading the (often bulkier) desktop versions. The RichFaces Mobile Showcase uses server-side MobileESP. The following is a custom MobileESP processor with CDI integration:
@ManagedBean(name="userAgent") @SessionScoped public class UserAgentProcessor implements Serializable { private static final long serialVersionUID = 1L; private UAgentInfo uAgentInfo; @PostConstruct public void init() { FacesContext context = FacesContext.getCurrentInstance(); HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest(); String userAgentStr = request.getHeader("user-agent"); String httpAccept = request.getHeader("Accept"); uAgentInfo = new UAgentInfo(userAgentStr, httpAccept); } public boolean isPhone() { //Detects a whole tier of phones that support similar functionality as the iphone return uAgentInfo.detectTierIphone(); } public boolean isTablet() { // Will detect iPads, Xooms, Blackberry tablets, but not Galaxy - they use a strange user-agent return uAgentInfo.detectTierTablet(); } public boolean isMobile() { return isPhone() || isTablet(); } }
RichFace's Facelets template then determines which page should be shown through Expression Language:
<f:view xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core" xmlns:c="http://java.sun.com/jsp/jstl/core" xmlns:ui="http://java.sun.com/jsf/facelets"> <c:choose> <c:when test="#{userAgent.phone}"> <ui:include src="phoneHome.xhtml"> [phone] </ui:include> </c:when> <c:when test="#{userAgent.tablet}"> <ui:include src="phoneHome.xhtml"> [tablet] </ui:include> </c:when> <c:otherwise> <ui:include src="desktopHome.xhtml"> [desktop] </ui:include> </c:otherwise> </c:choose> </f:view>