Detect Device Type In Java Web Application

2) user-agent-utils Example

It is Java user agent parser for processing user-agent strings. Can be used to handle http requests in real-time or to analyze log files.

Reference -> http://www.bitwalker.eu/software/user-agent-utils

Required Libraries

For using user-agent-utils, You need to have following classes (See below project structure for required classes)

  1. user-agent-utils

Project Structure

user-agent-utils Example

Detecting Device Type Of Web Application By Using user-agent-utils

Here we are creating a servlet we want to detect the device type(mobile or desktop) for the device that is sending the request.

package com.devicechecker;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import eu.bitwalker.useragentutils.OperatingSystem;
import eu.bitwalker.useragentutils.UserAgent;


/**
* This servlet is used to find the exact device type(desktop,mobile,tablet etc.) of client by scanning User-Agent string with the help of user-agent-utils api
*/

@WebServlet("/DeviceCheckerServlet")
public class DeviceCheckerServlet extends HttpServlet {
   
private static final long serialVersionUID = 1L;

  
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       
response.setContentType("text/html");
        response.setStatus
(HttpServletResponse.SC_OK);
        
        PrintWriter out = response.getWriter
();
        
       
// Get an UserAgentStringParser and analyze the requesting client
       
UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
        OperatingSystem agent = userAgent.getOperatingSystem
();
       
        out.append
("You're a <em>");
        out.append
(agent.getName());
        out.append
("</em> on <em>");
        out.append
(agent.getDeviceType().getName());
        out.append
("</em>!");
   
   
}
}
Output

From below, you can see that different requests leads to different output

Detect IPAD Device Type Using UserAgentUtils Detect IPhone Device Type Using UserAgentUtils Detect Tablet Type Using UserAgentUtils

3) Detecting Device Type By Using SpringFramework

If you use spring framework, then you can use spring in-built feature. By adding spring-mobile-device-1.0.1.RELEASE.jar in your classpath.

I have already mentioned this in my previous tutorial, you can see here





Previous 1 2








Your email address will not be published. Required fields are marked *