自学内容网 自学内容网

How to build and run this Java server?

To build and run the Java server using Spring Boot that we've discussed, follow these steps:

Prerequisites

Before you start, ensure you have the following installed on your machine:

  1. Java Development Kit (JDK): Install JDK 8 or later. You can download it from the Oracle website or use OpenJDK.
  2. Maven: Maven is a build automation tool used primarily for Java projects. You can download it from the Apache Maven website.
  3. IDE (Integrated Development Environment): You can use an IDE like IntelliJ IDEA or Eclipse for easier project management. You can also use a text editor like Visual Studio Code or even a simple text editor.

Steps to Build and Run the Server

Step 1: Create the Project Structure
  1. Create a New Directory: Create a new directory for your project. For example:

     

    bash

    mkdir FileDownloadServer
    cd FileDownloadServer
    
  2. Create the Directory Structure: Create the following directory structure:

    FileDownloadServer
    ├── src
    │   └── main
    │       ├── java
    │       │   └── com
    │       │       └── example
    │       │           └── filedownload
    │       │               ├── FileDownloadApplication.java
    │       │               └── FileDownloadController.java
    │       └── resources
    │           └── application.properties
    └── pom.xml
    
Step 2: Create the pom.xml File

Create a pom.xml file in the root of your project directory with the following content:

 

xml

<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.example</groupId>
    <artifactId>file-download-server</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <java.version>11</java.version>
        <spring.boot.version>3.2.0</spring.boot.version> <!-- Update to the latest stable version -->
    </properties>

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

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

xml

Step 3: Create the Java Files
  1. Create FileDownloadApplication.java: Create the FileDownloadApplication.java file in the src/main/java/com/example/filedownload/ directory:

     

    java

    package com.example.filedownload;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    @SpringBootApplication
    public class FileDownloadApplication {
        public static void main(String[] args) {
            SpringApplication.run(FileDownloadApplication.class, args);
        }
    }
    

    java

  2. Create FileDownloadController.java: Create the FileDownloadController.java file in the same directory:

     

    java

    package com.example.filedownload;
    
    import org.springframework.core.io.FileSystemResource;
    import org.springframework.http.HttpHeaders;
    import org.springframework.http.HttpStatus;
    import org.springframework.http.ResponseEntity;
    import org.springframework.web.bind.annotation.*;
    
    import java.io.File;
    
    @RestController
    @RequestMapping("/api")
    public class FileDownloadController {
    
        private static final String FILE_DIRECTORY = "files/"; // Directory where your files are stored
    
        @PostMapping("/download")
        public ResponseEntity<Object> downloadFile() {
            // Define the filename you want to send
            String filename = "example.txt"; // Change this filename based on your requirement
            File file = new File(FILE_DIRECTORY + filename);
    
            // Check if the file exists
            if (!file.exists() || !file.isFile()) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND)
                        .body("File not found");
            }
    
            // Prepare the response with the file
            HttpHeaders headers = new HttpHeaders();
            headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + filename);
    
            // Create a FileSystemResource from the file
            FileSystemResource fileResource = new FileSystemResource(file);
    
            // Create the response with the file resource
            return ResponseEntity.ok()
                    .headers(headers)
                    .body(fileResource);
        }
    }
    

    java

Step 4: Create the files Directory

Create a files directory in the root of your project (the same level as src and pom.xml). Place a file named example.txt (or whichever filename you choose) in this directory.

Step 5: Build the Project

  1. Open a terminal/command prompt.

  2. Navigate to the root of your project directory (where your pom.xml is located).

  3. Run the following Maven command to build the project:

     

    bash

    mvn clean install
    

This command compiles the Java files, runs tests (if any), and packages the application into a JAR file.

Step 6: Run the Application

Once the build is successful, you can run the application using the following command:

 

bash

mvn spring-boot:run

Alternatively, if you want to run the JAR directly after building, you can use:

  1. Navigate to the target directory created after the build. You will find a JAR file named file-download-server-1.0-SNAPSHOT.jar (the name may vary slightly based on your setup).

  2. Run the JAR file with:

     

    bash

    java -jar target/file-download-server-1.0-SNAPSHOT.jar
    

Step 7: Test the API

You can now test the API using tools like Postman or curl. Here’s how to make a request using curl:

 

bash

curl -X POST http://localhost:8080/api/download

Summary

Following these steps will set up your Spring Boot application, allowing you to run a server that serves a file when requested via a POST API endpoint. Make sure to modify the filename variable in the FileDownloadController to suit your requirements. If you have any questions or need further assistance, feel free to ask!


原文地址:https://blog.csdn.net/m0_68739984/article/details/142879810

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!