Book Image

SPRING COOKBOOK

By : Jerome Jaglale, Yilmaz
Book Image

SPRING COOKBOOK

By: Jerome Jaglale, Yilmaz

Overview of this book

This book is for you if you have some experience with Java and web development (not necessarily in Java) and want to become proficient quickly with Spring.
Table of Contents (14 chapters)
13
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...