很多工程都是有pc端和mobile端的,并且这里的mobile端并不是指移动端适应的效果,而是专门为mobile端编写的。 所以这样一个页面就会用到两套页面代码(pc端和mobile端),例如imooc或csdn这样的平台。
pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--页面模板-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!--热部署-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
</dependencies>
<build>
<!--指定项目输出文件名,即jar/war包的包名-->
<finalName>factory</finalName>
<!--插件-->
<plugins>
<!--maven打包插件-->
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
pc/index
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<!--网站图标-->
<link rel="shortcut icon" href="" th:href="@{/image/favicon.ico}"/>
<title>pc端</title>
</head>
<body>
<h1>这是PC端界面</h1>
</body>
</html>
mobile/index
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<!--网站图标-->
<link rel="shortcut icon" href="" th:href="@{/image/favicon.ico}"/>
<title>手机端</title>
</head>
<body>
<h1>手机端</h1>
</body>
</html>
步骤 1
创建一个接口:
public interface Device {
String getIndex() ;
}
步骤 2 创建实现接口的实体类
public class PcDevice implements Device{
public String getIndex() {
return "pc/index";
}
}
public class MobileDevice implements Device{
public String getIndex() {
return "mobile/index";
}
}
步骤 3 创建一个工厂,根据传递的参数信息创建实现类对象。
import javax.servlet.http.HttpServletRequest;
public class DeviceFactory {
public static Device getDevice(HttpServletRequest request) {
String userAgent = request.getHeader("user-agent"); //获取请求头信息
//判断当前是pc电脑端还是mobile手机端
if(userAgent.indexOf("Windows NT") != -1) {
return new PcDevice();
}else if(userAgent.indexOf("Android") != -1 || userAgent.indexOf("iPhone") != -1) {
return new MobileDevice();
}else {
return null;
}
}
}
步骤 4 使用该工厂,通过传递参数信息获取指定指定实现类对象。
@Controller
public class IndexController {
@RequestMapping("/index")
public String demo(HttpServletRequest request){
Device d = DeviceFactory.getDevice(request);
return d.getIndex();
}
}