SpringBoot 创建web,并打包部署到服务器的Tomcat

SpringBoot 创建web,并打包部署到服务器的Tomcat

摘要:
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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
对于Spring Boot和Vue的前后端分离项目,你可以按照以下步骤进行打包部署服务器: 1. 后端部署: - 将Spring Boot项目打包成可执行的JAR文件。可以使用Maven或Gradle构建工具进行打包。 - 将打包好的JAR文件上传到服务器上。 - 在服务器上安装Java运行环境,并配置好环境变量。 - 使用命令行运行JAR文件,命令类似于 `java -jar your-application-name.jar`。 2. 前端部署: - 在本地使用Vue的构建工具(如Vue CLI)进行项目构建。运行 `npm run build` 命令将前端代码打包成静态资源。 - 将打包生成的静态资源文件上传到服务器上的合适目录。 3. 部署Web容器: - 安装和配置一个Web容器,如Apache Tomcat或Nginx。 - 配置Web容器的虚拟主机或代理设置,将后端请求转发到Spring Boot应用的地址和端口。 - 将前端打包生成的静态资源文件部署Web容器中,通过配置访问路径映射到对应的URL。 4. 配置数据库: - 如果你的项目使用了数据库,确保在服务器上安装了相应的数据库,并且创建了对应的数据库和表结构。 - 在Spring Boot项目的配置文件中配置数据库连接信息,确保应用能够连接到数据库。 5. 启动应用: - 启动后端应用,运行Spring Boot项目的JAR文件。 - 启动Web容器,确保前端静态资源能够被访问到。 通过以上步骤,你就可以将Spring Boot和Vue的前后端分离项目成功打包部署服务器上了。请根据你的具体情况和服务器环境进行相应的配置和调整。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值