---
title: "基于Spring提供支持不同设备的页面"
author: "thinkerAndThinker"
date: "2017-07-17T19:55:59Z"
tags: []
categories: ["企业架构"]
slug: "spring"
draft: false
lastmod: "2017-07-17T19:55:59Z"
id: 2383989
url: "https://javatea.iteye.com/blog/2383989"
---

基于[spring](http://lib.csdn.net/base/javaee "Java EE知识库")来检测访问Web页面的设备是很简单的，在这个[经验](http://tianmaying.com/tutorial/spring-device-detection)中我们讲到过。通常不同的设备访问我们是通过响应式设计来统一处理各种设备的尺寸的。但是如果希望针对不同的设备，显示不同的内容呢？ Spring对于这一点同样提供了很好的支持，来看看如何实现。

## []()准备工作

我们通过一个简单的例子来演示，基于Spring MVC来实现一个简单的HTTP GET请求，访问的地址是：

`http://localhost:8080/greeting`

- 如果从桌面浏览器访问这个地址，则返回的页面中显示:`Say hello from desktop`
- 如果从手机浏览器访问这个地址：则返回的页面中显示`Say hello from mobile`
- 如果从平板电脑访问这个地址：则返回的页面中显示`Say hello from tablets`

先该准备好开发环境：

- IDE+Java环境（JDK 1.7或以上版本）
- Maven 3.0+（Eclipse和Idea IntelliJ内置，如果使用IDE并且不使用命令行工具可以不安装）

Maven POM文件的设置

`pom.xml`

```
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.tianmaying.mobilecontent</groupId>
  <artifactId>content-for-multiple-device</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>content-for-multiple-device</name>
  <description>Demo of serving different content for desktop, mobile and tablet device</description>

  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.2.5.RELEASE</version>
    <relativePath/>
  </parent>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <java.version>1.8</java.version>
  </properties>

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

  <build>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
      </plugin>
    </plugins>
  </build>

</project>
```

## []()创建Properties文件

Spring Boot能够针对不同设备渲染不同的视图（View），只需要在应用的Properties文件中中稍加配置即可。在src/main/resources/application.properties文件（没有这个文件，则自己创建这个文件）中增加一行：

`spring.mobile.devicedelegatingviewresolver.enabled: true`

针对一个请求，`LiteDeviceDelegatingViewResolver`通过`DeviceResolverHandlerInterceptor`识别出的`Device`类型来判断返回哪种视图进行响应（桌面、手机还是平板），这一部分大家参考[Spring如何识别设备的经验](http://tianmaying.com/tutorial/spring-device-detection)。

在这个例子中， `LiteDeviceDelegatingViewResolver`会将请求代理给`ThymeleafViewResolver`，作为Spring自身提供的正牌`ViewResolver`，相比传统的视图技术如JSP，Velocity等，有不少过人之处，大家可以回顾一下[Thymeleaf的介绍](http://tianmaying.com/tutorial/using-thymeleaf)以及如何在Spring MVC中[使用Thymeleaf](http://tianmaying.com/tutorial/spring-mvc-thymeleaf)。默认情况下，Spring Boot去到\*\*mobile/和tablet/\*\*文件下去寻找移动端和平板端对应的视图进行渲染。当然你也可以在属性文件中进行设置，约定大于配置，没有特别需求用约定就好了。

## []()创建Controller

Spring Boot的请求都是通过Controller的处理的。Controller的实现非常简单：

- 通过`@Controller`标注一个普通的类
- 通过`@RequestMapping`标注一个方法，设置该方法响应的URL地址和方法（ 如`@RequestMapping(method=GET` ）
- 在方法中填入Model，返回视图的名称

`SayHelloController`

```
package com.tianmaying.mobilecontent;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class SayHelloController {

    @RequestMapping("/sayHello")
    public String greeting() {
        return "sayHello";
    }

}
```

## []()创建视图

最后让我们来创建Thymeleaf的视图模板，这里没什么模型的数据需要填充，只需要显示一句话即可：

`sayHello.html`

```
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Getting Started: Serving Web Content</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
    <p th:text="'Say hello from desktop'" />
</body>
</html>
```

接下来我们创建存放移动端模板和平板端模板的目录：

```
└── src
    └── main
        └── resources
            └── templates
                └── greeting.html
                └── mobile
                    └── greeting.html
                └── tablet
                    └── greeting.html
```

在mobile和tablet目录下的HTML文件，内容大多是一样的，唯一不同的就是`<p>`标签，分别为：

`<p th:text="'Say hello from mobile'" />`

`<p th:text="'Say hello from tablet'" />`

## []()测试

最后我们通过`main()`函数将这个`SpringBootApplication` Run起来：

`App.Java`

```
package com.tianmaying.mobilecontent;

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

@SpringBootApplication
public class App {

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

}
```

大家从不同的设备上访问http://localhost:8080/sayHello就能看到效果了。