Detecting mobiles and tablets
In this recipe, you'll learn how, from a controller method, you can detect whether the current HTTP request has come from a desktop computer, mobile, or tablet.
How to do it…
Register a DeviceResolverHandlerInterceptor
interceptor and use DeviceUtils
in the controller method:
In the Spring configuration class, declare a
DeviceResolverHandlerInterceptor
bean:@Bean public DeviceResolverHandlerInterceptor deviceResolverHandlerInterceptor() { return new DeviceResolverHandlerInterceptor(); }
Register the
DeviceResolverHandlerInterceptor
bean as an interceptor in theaddInterceptors()
method:@Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(deviceResolverHandlerInterceptor()) ; }
Add an
HttpServletRequest
argument to your controller method:@Controller public class UserController { @RequestMapping("/user_list") public void userList(HttpServletRequest request) {
Use
DeviceUtils.getCurrentDevice()
to generate aDevice
object...