摘要:
Android开发中免不了需要自己编写后台接口测试,今天使用SpringBoot创建一个web,后台的功能实现文件的上传下载,并打包部署到服务器的Tomcat.。SpringBoot比SpringMVC,SSH等框架更容易上手。适合快速搭建一个简单的后台。
1、创建web项目
在创建第一个web项目的之前,需要安装tomcat,Maven。这里不讲环境配置。
1、new project 选择 Spring Initializer,选择java 8(和本地java环境以及部署化解一致即可)
打包方式选择war,也可以在完成项目构建后在pom.xml中配置
先一步勾选web->Spring web 第一次构建由于maven环境需要下载很多东西,会比较慢。
项目结构如下,和android studio 一样
src方java文件,我们的控制器就放在这下面,
resources的static文件夹下面可以放置我们的html文件
pom.xml类似AS的build.gradle文件添加依赖和项目全局配置
2、编写相关代码
1、我们需要一个html显示界面
创建文件resources.static.index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>文件上传</title>
</head>
<body>
<form action="file/upload" enctype="multipart/form-data" method="post">
<input name="file" type="file"/>
<input type="submit" value="上传"/>
</form>
<a href="file/download">文件下载</a>
<p/>
<a href="file/downloadZip">ZIP文件下载</a>
<br/>
</body>
</html>
这里简单讲述一下这个HTML文件,
一个form表单和两个超链接,file/download的file和下面的FileController的注释@RequestMapping("/file")的值一致,download和FileController.download()的注释@GetMapping("/download")一致。
href=“file/download"不要写成href=”/file/download"否则在部署项目的时候会报404。
2、编写Controller实现后台功能
创建Controller文件夹,在下面创建文件FileController,由FileController提供API
@RestController
@RequestMapping("/file")
@Slf4j
public class FileController {
@Value("${filepath}")//解析application.properties中的配置
private String filepath;
/**
* 处理文件上传
*/
@PostMapping(value = "/upload")
public String upload(@RequestParam("file")MultipartFile file){
File targetFile = new File(filepath);
if (!targetFile.exists()) {
targetFile.mkdirs();
}
try (FileOutputStream out = new FileOutputStream(filepath + file.getOriginalFilename());) {
out.write(file.getBytes());
} catch (Exception e) {
e.printStackTrace();
log.error("文件上传失败!");
return "uploading failure";
}
log.info("文件上传成功!");
return "uploading success";
}
/**
* 访问方式:http://localhost:8080/file/download
* http://localhost:8080/file/download?filename=tmp.txt
* 部署到tomcat下的访问的时候链接是
* http://localhost:8080/springbootweb01/file/download
* 其中springbootweb01不是项目名称是pom.xml配置的“finalName”
* @param response
*/
@GetMapping("/download")
public void download(HttpServletResponse response){
String filename = null;
String filePath = "D:/ideafile";//本地存储文件的路径
HttpServletRequest request =
((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
filename = request.getParameter("filename");//获取请求链接中的filename属性
if(filename == null || "".equals(filename)){
filename = "tem.txt";//返回默认文件
}
File file = new File(filePath + "/" + filename);
if (file.exists()) {
try (FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis)) {
response.setContentType("application/octet-stream");
response.setHeader("content-type", "application/octet-stream");
response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(filename, "utf8"));
byte[] buffer = new byte[1024];
//输出流
OutputStream os = response.getOutputStream();
int i = bis.read(buffer);
while (i != -1) {
os.write(buffer);
i = bis.read(buffer);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.3</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.wust.linliang</groupId>
<artifactId>SpringBootWeb01</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>SpringBootWeb01</name>
<description>SpringBootWeb01</description>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.32</version>
</dependency>
<!-- https://mvnrepository.com/artifact/ch.qos.logback/logback-classic -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.junit.jupiter/junit-jupiter-api -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.7.1</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
<finalName>springbootweb01</finalName>
</build>
</project>
3、部署
1、和在ide中测试不同
需要修改SpringBootWeb01Application.java,让其继承SpringBootServletInitializer
public class SpringBootWeb01Application extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(SpringBootWeb01Application.class);
}
public static void main(String[] args) {
SpringApplication.run(SpringBootWeb01Application.class, args);
}
}
2、修改pom.xml文件
添加war
在pom.xml的build下添加springbootweb01这是我们打包出来的war的文件名
3、打包war,双击maven的intall
D:\IdeaProjects\SpringBoot\SpringBootWeb01\target\springbootweb01.war
在工程下的tartget下生产war,放到tomcat的webapp下,放进去之后会被自动解压为文件夹,启动tomcat,浏览器输入:
http://localhost:8080/springbootweb01/index.html
Git链接:https://github.com/linliangliang/SpringBoot
这里提供一个简单的在线查看github代码的方式,只需要加个1s,就不用下载后阅览了。
:https://github1s.com/linliangliang/SpringBoot