Wednesday, 16 April 2014

Handling mobile and desktop application with single URL in java.

Recent trend is to create two separate application that compatible for desktop browser and mobile browser.So user automatically switch to their URL according to the device from which they access the site .

Normally in mobile site we are include only necessary information due to space constrain. So data layer and business layer of the application also have some minor changes.that means we need to handle this separate.Checking user-agent and change logic according to user-agent in each page is very difficult.

We can create one application that switch URL according to the user-agent (field in HTTP request contain the client information like browser name ,device name,OS etc ) . Point this application to the domain name.

Example:- we have two application one for mobile device and another for desktop
Mobile URL :- IP:port/mobile/*
desktop URL :- IP:port/*
URL switching applicaion :- IP1:port
Domain name :-
Our Domain name pointing to the IP1:port that switch URL according to the user-agent. if the user type URL as it goes to the IP1:port and switch the user to different URL according to the user-agent.

Problem is if user trying to access mobile site (IP:port/mobile/*) from desktop browser, mobile site will render in desktop browser. this is a bad practice in user point of view (look and feel of application will awful if we render mobile site in desktop browser).

To handling this scenario we can write filter for IP:port application.

1. Create filter that check user-agent field in HTTP request and if it is from mobile will goes to IP:port/mobile/
Example :-

public class DesktopFilter implements Filter{

* properties
private static Properties properties = new Properties();

private static final String IPAD_URL = "abac.ipad.url";

public void destroy() {
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
try {
String userAgent = ((HttpServletRequest)request).getHeader("User- Agent");
if(userAgent == null){
userAgent = "";
properties.load(getClass().getResourceAsStream (""));
chain.doFilter(request, response);
} catch (Exception ex){
chain.doFilter(request, response);
public void init(FilterConfig arg0) throws ServletException {

2. Create filter lib file and place this file either in application(IP:port) lib / server lib.

3.We can include filter mapping either in application web.xml or server web.xml, if your server dedicate to you application then you can freely use server web.xml . otherwise you should careful add filter mapping in web.xml.

If user access application from desktop by using
1. :- it will redirect to IP:port/*
2. IP:port/mobile/* :- it will redirect to IP:port/mobile/*

No comments:

Post a Comment