A Guide to Spring Mobile – Spring手机指南

最后修改: 2017年 1月 31日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

Spring Mobile is a modern extension to the popular Spring Web MVC framework that helps to simplify the development of web applications, which needs to be fully or partially compatible with cross device platforms, with minimal effort and less boilerplate coding.

Spring Mobile是流行的Spring Web MVC框架的现代扩展,有助于简化Web应用程序的开发,这些应用程序需要完全或部分地兼容跨设备平台,只需花费最少的精力和较少的模板编码。

In this article, we’ll learn about the Spring Mobile project, and we would build a sample project to highlight uses of Spring Mobile.

在这篇文章中,我们将了解Spring Mobile项目,并建立一个示例项目来强调Spring Mobile的用途。

2. Features of Spring Mobile

2.Spring Mobile的特点

  • Automatic Device Detection: Spring Mobile has built-in server-side device resolver abstraction layer. This analyzes all incoming requests and detects sender device information, for example, a device type, an operating system, etc
  • Site Preference Management: Using Site Preference Management, Spring Mobile allows users to choose mobile/tablet/normal view of the website. It’s comparatively deprecated technique since by using DeviceDelegatingViewresolver we can persist the view layer depending on the device type without demanding any input from the user side
  • Site Switcher: Site Switcher is capable of automatically switch the users to the most appropriate view according to his/her device type (i.e. mobile, desktop, etc.)
  • Device Aware View Manager: Usually, depending on device type we forward the user request to a specific site meant to handle specific device. Spring Mobile’s View Manager lets developer the flexibility to put all of the views in pre-defined format and Spring Mobile would auto-mange the different views based on device type

3. Building an Application

3.建立一个应用程序

Let’s now create a demo application using Spring Mobile with Spring Boot and Freemarker Template Engine and try to capture device details with a minimal amount of coding.

现在让我们使用Spring Boot的Spring Mobile和Freemarker模板引擎创建一个演示应用程序,并尝试用最少的编码捕获设备的细节。

3.1. Maven Dependencies

3.1.Maven的依赖性

Before we start we need to add following Spring Mobile dependency in the pom.xml:

在我们开始之前,我们需要在pom.xml中添加以下Spring Mobile依赖。

<dependency>
    <groupId>org.springframework.mobile</groupId>
    <artifactId>spring-mobile-device</artifactId>
    <version>2.0.0.M3</version>
</dependency>

Please note that the latest dependency is available in Spring Milestones repository, so let’s add this in our pom.xml as well:

请注意,最新的依赖关系在Spring Milestones仓库中是可用的,所以我们也要在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>

3.2. Create Freemarker Templates

3.2.创建Freemarker模板

First, let’s create our index page using Freemarker. Don’t forget to put necessary dependency to enable autoconfiguration for Freemarker.

首先,让我们使用Freemarker创建我们的索引页。不要忘记为Freemarker的自动配置设置必要的依赖性。

Since we are trying to detect the sender device and route the request accordingly, we need to create three separate Freemarker files to address this; one to handle a mobile request, another one to handle tablet and the last one (default) to handle normal browser request.

由于我们试图检测发件人设备,并相应地路由请求,我们需要创建三个独立的Freemarker文件来解决这个问题;一个处理移动请求,另一个处理平板电脑,最后一个(默认)处理普通浏览器请求。

We need to create two folders named ‘mobile‘ and ‘tablet‘ under src/main/resources/templates and put the Freemarker files accordingly. The final structure should look like this:

我们需要在src/main/resources/templates下创建两个名为’mobile‘和’tablet‘的文件夹,并相应地放置Freemarker文件。最后的结构应该是这样的。

└── src
    └── main
        └── resources
            └── templates
                └── index.ftl
                └── mobile
                    └── index.ftl
                └── tablet
                    └── index.ftl

Now, let’s put the following HTML inside index.ftl files:

现在,让我们把以下HTML放在index.ftl文件内。

<h1>You are into browser version</h1>

Depending on the device type, we’ll change the content inside the <h1> tag,

根据设备类型,我们将改变<h1>tag里面的内容。

3.3. Enable DeviceDelegatingViewresolver

3.3.启用DeviceDelegatingViewresolver

To enable Spring Mobile DeviceDelegatingViewresolver service, we need to put the following property inside application.properties:

为了启用Spring Mobile的DeviceDelegatingViewresolver服务,我们需要在application.properties:中放入以下属性。

spring.mobile.devicedelegatingviewresolver.enabled: true

Site preference functionality is enabled by default in Spring Boot when you include the Spring Mobile starter. However, it can be disabled by setting the following property to false:

在Spring Boot中,当你包含Spring Mobile启动器时,网站偏好功能是默认启用的。但是,可以通过将以下属性设置为false来禁用它。

spring.mobile.sitepreference.enabled: true

3.4. Add Freemarker Properties

3.4.添加自由标记属性

For Spring Boot to be able to find and render our templates, we need to add the following to our application.properties:

为了让Spring Boot能够找到并渲染我们的模板,我们需要在application.properties中添加以下内容。

spring.freemarker.template-loader-path: classpath:/templates
spring.freemarker.suffix: .ftl

3.5. Create a Controller

3.5.创建一个控制器

Now we need to create a Controller class to handle the incoming request. We would use simple @GetMapping annotation to handle the request:

现在我们需要创建一个Controller类来处理进入的请求。我们将使用简单的@GetMapping注解来处理该请求。

@Controller
public class IndexController {

    @GetMapping("/")
    public String greeting(Device device) {
		
        String deviceType = "browser";
        String platform = "browser";
        String viewName = "index";
		
        if (device.isNormal()) {
            deviceType = "browser";
        } else if (device.isMobile()) {
            deviceType = "mobile";
            viewName = "mobile/index";
        } else if (device.isTablet()) {
            deviceType = "tablet";
            viewName = "tablet/index";
        }
        
        platform = device.getDevicePlatform().name();
        
        if (platform.equalsIgnoreCase("UNKNOWN")) {
            platform = "browser";
        }
     	
        return viewName;
    }
}

A couple of things to note here:

这里有几件事要注意。

  • In the handler mapping method, we are passing org.springframework.mobile.device.Device. This is the injected device information with each request. This is done by DeviceDelegatingViewresolver which we have enabled in the apllication.properties
  • The org.springframework.mobile.device.Device has a couple of inbuilt methods like isMobile(), isTablet(), getDevicePlatform() etc. Using these we can capture all device information we need and use it

3.6. Java Config

3.6. Java配置

To enable device detection in a Spring web application, we also need to add some configuration:

为了在Spring Web应用程序中启用设备检测,我们还需要添加一些配置。

@Configuration
public class AppConfig implements WebMvcConfigurer {

    @Bean
    public DeviceResolverHandlerInterceptor deviceResolverHandlerInterceptor() { 
        return new DeviceResolverHandlerInterceptor(); 
    }

    @Bean
    public DeviceHandlerMethodArgumentResolver deviceHandlerMethodArgumentResolver() { 
        return new DeviceHandlerMethodArgumentResolver(); 
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) { 
        registry.addInterceptor(deviceResolverHandlerInterceptor()); 
    }

    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
        argumentResolvers.add(deviceHandlerMethodArgumentResolver()); 
    }
}

We are almost done. One last thing to do is to build a Spring Boot config class to start the application:

我们就快完成了。最后一件事是建立一个Spring Boot配置类来启动应用程序。

@SpringBootApplication
public class Application {

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

4. Testing the Application

4.测试应用程序

Once we start the application, it will run on http://localhost:8080.

一旦我们启动应用程序,它将在http://localhost:8080上运行。

We will use Google Chrome’s Developer Console to emulate different kinds of device. We can enable it by pressing ctrl + shift + i or by pressing F12.

我们将使用谷歌浏览器的开发者控制台来模拟不同种类的设备。我们可以通过按ctrl + shift + i或按F12来启用它。

By default, if we open the main page, we could see that Spring Web is detecting the device as a desktop browser. We should see the following result:

默认情况下,如果我们打开主页面,我们可以看到Spring Web正在将设备检测为一个桌面浏览器。我们应该看到以下结果。

browser-300x32

 

Now, on the console panel, we click the second icon on the top left. It would enable a mobile view of the browser.

现在,在控制台面板上,我们点击左上方的第二个图标。它将启用浏览器的移动视图。

We could see a drop-down coming in the top left corner of the browser. In the drop-down, we can choose different kinds of device type. To emulate a mobile device let’s choose Nexus 6P and refresh the page.

我们可以看到在浏览器的左上角有一个下拉框。在下拉菜单中,我们可以选择不同种类的设备类型。为了模拟移动设备,让我们选择Nexus 6P并刷新页面。

As soon as we refresh the page, we’ll notice that the content of the page changes because DeviceDelegatingViewresolver has already detected that the last request came from a mobile device. Hence, it passed the index.ftl file inside the mobile folder in the templates.

只要我们刷新页面,我们就会注意到页面的内容发生了变化,因为DeviceDelegatingViewresolver已经检测到最后一个请求来自移动设备。因此,它将index.ftl文件传递到模板的移动文件夹内。

Here’s the result:

结果是这样的。

mobile

In the same way, we are going to emulate a tablet version. Let’s choose iPad from the drop-down just like the last time and refresh the page. The content would be changed, and it should be treated as a tablet view:

以同样的方式,我们要模拟一个平板电脑版本。让我们像上次一样从下拉菜单中选择iPad,然后刷新页面。内容将被改变,它应该被当作平板电脑视图。

tablet

Now, we’ll see if Site Preference functionality is working as expected or not.

现在,我们来看看网站偏好功能是否按预期工作。

To simulate a real time scenario where the user wants to view the site in a mobile friendly way, just add following URL parameter at the end of default URL:

为了模拟一个实时场景,用户希望以移动友好的方式查看网站,只需在默认URL的末尾添加以下URL参数。

?site_preference=mobile

Once refreshed, the view should be automatically moved to mobile view i.e. following text would be displayed ‘You are into mobile version’.

一旦刷新,视图应自动转移到移动视图,即显示以下文字 “您正在进入移动版本”。

In the same way to simulate tablet preference, just add following URL parameter at the end of default URL:

用同样的方法来模拟平板电脑的偏好,只需在默认URL的末尾添加以下URL参数。

?site_preference=tablet

And just like the last time, the view should be automatically refreshed to tablet view.

就像上次一样,视图应该会自动刷新为平板电脑视图。

Please note that the default URL would remain as same, and if the user again goes through default URL, the user will be redirected to respective view based on device type.

请注意,默认的URL将保持不变,如果用户再次通过默认的URL,用户将被重定向到基于设备类型的相应视图。

5. Conclusion

5.结论

We just created a web application and implemented the cross-platform functionality. From the productivity perspective, it’s a tremendous performance boost. Spring Mobile eliminates many front-end scripting to handle cross-browser behavior, thus reducing development time.

我们只是创建了一个网络应用程序并实现了跨平台的功能。从生产力的角度来看,这是一个巨大的性能提升。Spring Mobile消除了许多处理跨浏览器行为的前端脚本,从而减少了开发时间。

Like always, updated source code are over on GitHub.

像往常一样,更新的源代码在GitHub上