[该教程翻译自Spring官方,并进行适当删减。]
你将搭建的
创建一个Spring MVC项目,来探测访问网站的设备类型(手机、电脑、平板),并动态切换呈现的视图。
工具
一个文本编辑器,JDK1.6及以上,Maven 3.0+或者Gradle 1.11+。(本文将使用Maven)
pom.xml清单:
4.0.0
org.springframework
gs-device-detection
0.1.0
org.springframework.boot
spring-boot-starter-parent
1.1.5.RELEASE
org.springframework.boot
spring-boot-starter-web
org.springframework.mobile
spring-mobile-device
hello.Application
maven-compiler-plugin
org.springframework.boot
spring-boot-maven-plugin
spring-releases
Spring Milestone Repository
http://repo.spring.io/libs-release
spring-releases
Spring Milestone Repository
http://repo.spring.io/libs-release
新建项目
首先你新建一个符合Maven规范的目录结构, src/main/java/hello
观察pom.xml,我们发现了新增的Spring Mobile依赖,这样Spring Boot就自动配置DeviceResolverHandlerInterceptor和DeviceHandlerMethodArgumentResolver。前者(DeviceResolverHandlerInterceptor)在前往的请求内检查User-Agent头,通过头信息,可以判断是来自手机还是电脑或者平板。而后者(DeviceHandlerMethodArgumentResolver)允许Spring MVC在一个控制器方法内使用解析过的Device对象。
下面是控制器的清单:
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!";
}
}
Application类如下:
package hello;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.SpringApplication;
import org.springframework.context.annotation.ComponentScan;
@ComponentScan
@EnableAutoConfiguration
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
@EnableAutoConfiguration是基于当前类加载路径的内容,切换到合理的默认配置。如本应用需要默认内置tomcat的配置(tomcat-embed-core.jar)和Spring MVC的默认配置(spring-webmvc.jar)。
java -jar target/gs-device-detection-0.1.0.jar
电脑浏览器访问:
笔者IP是 192.168.1.106,使用手机访问,