Detecting a mobile device with spring-boot

2019-06-14 12:38发布

问题:

I am trying to get my application to detect a mobile device and render that page but I am getting no response but my index.html page is rendering. It is completely ignoring my mobile controller.

@Controller
public class DeviceDetection {

    @RequestMapping("/")
    public @ResponseBody String detectDevice(Device device) {

        if (device.isNormal()) {
            System.out.println("Inside isNormal()");
            return "index";

        } else if (device.isMobile()) {
            System.out.println("Inside isMobile()");
            return "mobilePage";
        } else if (device.isTablet()) {
            return "mobilePage";
        }
        return "index";
    }

}

pom.xml

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mobile</artifactId>
        </dependency>

回答1:

spring-boot-mobile requires additional property to be set in order to detect your Device.

The property is spring.mobile.devicedelegatingviewresolver.enabled: true

The following is default directories structure:

        resources
        └── templates
            └── greeting.html
            └── mobile
                └── greeting.html
            └── tablet
                └── greeting.html

In your case you need to map your templates correctly.

Spring Boot spring-mobile properties to customize behavior:

spring.mobile.devicedelegatingviewresolver.enable-fallback=false - Enable support for fallback resolution.

spring.mobile.devicedelegatingviewresolver.enabled=false - Enable device view resolver

spring.mobile.devicedelegatingviewresolver.mobile-prefix=mobile/- Prefix that gets prepended to view names for mobile devices.

spring.mobile.devicedelegatingviewresolver.mobile-suffix=- Suffix that gets appended to view names for mobile devices.

spring.mobile.devicedelegatingviewresolver.normal-prefix= - Prefix that gets prepended to view names for normal devices.

spring.mobile.devicedelegatingviewresolver.normal-suffix=- Suffix that gets appended to view names for normal devices.

spring.mobile.devicedelegatingviewresolver.tablet-prefix=tablet/- Prefix that gets prepended to view names for tablet devices.

spring.mobile.devicedelegatingviewresolver.tablet-suffix=- Suffix that gets appended to view names for tablet devices.

spring.mobile.sitepreference.enabled=true- Enable SitePreferenceHandler.

Also I would change @RequestMapping("/") to something else.