有时候我们有这种需求,想在同一个方法中判断发起请求的设备,并跳转到对应的页面,可能有不少人会写多个Controller
或者方法以对应不同的请求设备,但这样的写法非常不优雅。
这里要介绍的是Spring Mobile
这个框架,官网的描述:它提供了检测向Spring web
站点发出请求的设备类型的功能,并提供基于该设备的其他视图。像所有的Spring
项目一样,Spring Mobile
的真正威力在于它的可扩展性。下面我们使用代码来说明。
本文示例代码基于Spring Boot 2.2.7
、JDK1.8
。
全部代码Gitee
地址:https://gitee.com/qiwan/spring-mobile-demo
1.首先在pom.xml
中引用以下依赖:
<dependency>
<groupId>org.springframework.mobile</groupId>
<artifactId>spring-mobile-device</artifactId>
<version>2.0.0.M3</version>
</dependency>
<!-- 以上引用的jar包不在maven库中,故需要在pom.xml中添加以下库 -->
<repositories>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/libs-milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
2.创建WebMvcConfig
类实现WebMvcConfigurer
接口,并重写addInterceptors
和addArgumentResolvers
两个方法:
import java.util.List;
import org.springframework.context.annotation.Configuration;
import org.springframework.mobile.device.DeviceHandlerMethodArgumentResolver;
import org.springframework.mobile.device.DeviceResolverHandlerInterceptor;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new DeviceResolverHandlerInterceptor());
}
@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
argumentResolvers.add(new DeviceHandlerMethodArgumentResolver());
}
}
3.创建Controller
类并编写方法:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.mobile.device.Device;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/")
public class DeviceController {
private static final Logger log = LoggerFactory.getLogger(DeviceController.class);
@RequestMapping("device")
public String device(Device device) { //注入Device类
if (device.isMobile()) {
log.info("========请求来源设备是手机!========");
return "mobile/index";
} else if (device.isTablet()) {
log.info("========请求来源设备是平板!========");
return "tablet/index";
} else {
log.info("========请求来源设备是其它!========");
return "index";
}
}
}
4.三个index.html
页面所在的目录结构如下:
src/main/resources
--static
--templates
--mobile
index.html
--tablet
index.html
index.html
application.properties
启动服务并从多端浏览器发起请求,可发现方法跳转到了对应的页面。