Spring之检测设备类型

本文介绍了如何在Spring MVC应用中检测访问设备类型,包括自动配置DeviceResolverHandlerInterceptor用于解析User-Agent判断浏览器、手机或平板,并使用DeviceHandlerMethodArgumentResolver将Device对象传递到Controller。创建的Controller使用@ResponseBody注解,当通过PC浏览器访问http://localhost:8080/detect-device时,会返回'Hello normal browser!'。
摘要由CSDN通过智能技术生成

Detecting a Device

目标:
创建一个可以检测出访问你的站点的设备类型的MVC应用
以便动态的切换适配于设备的视图

自动配置
- DeviceResolverHandlerInterceptor:
自动解析请求头中的“User-Agent“,来判断请求来自以下三种设备之一
1、普通浏览器
2、手机浏览器
3、平板浏览器
- DeviceHandlerMethodArgumentResolver:
允许Spring MVC 使用解析出来的Device对象传递到Controller的方法中。

创建一个Controller

package hello;

import org.springframework.mobile.device.Device;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class DeviceDetectionController {

    @RequestMapping("/detect-device")
    public @ResponseBody String detectDevice(Device device) {
        String deviceType = "unknown";
        if (device.isNormal()) {
            deviceType = "normal";
        } else if (device.isMobile()) {
            deviceType = "mobile";
        } else if (device.isTablet()) {
            deviceType = "tablet";
        }
        return "Hello " + deviceType + " browser!";
    }

}

@ResponseBody注解告诉Spring MVC把返回的Object直接写到
Response body(响应体),而不是渲染model到一个视图中。

运行Application

package hello;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}

测试:
通过PC端浏览器访问http://localhost:8080/detect-device返回以下信息:
Hello normal browser!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值