Book Image

SPRING COOKBOOK

Book Image

SPRING COOKBOOK

Overview of this book

Table of Contents (19 chapters)
Spring Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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:

  1. In the Spring configuration class, declare a DeviceResolverHandlerInterceptor bean:

    @Bean
    public DeviceResolverHandlerInterceptor deviceResolverHandlerInterceptor() {
        return new DeviceResolverHandlerInterceptor();
    }
  2. Register the DeviceResolverHandlerInterceptor bean as an interceptor in the addInterceptors() method:

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(deviceResolverHandlerInterceptor()) ;
    }
  3. Add an HttpServletRequest argument to your controller method:

    @Controller
    public class UserController {  
      @RequestMapping("/user_list")
      public void userList(HttpServletRequest request) {
  4. Use DeviceUtils.getCurrentDevice() to generate a Device object...