1. 首页
  2. 软件开发
  3. JAVA
  4. spring boot 开发接口

spring boot 开发接口

  • 发布于 2024-08-14
  • 0 次阅读

本文由 简悦 SimpRead 转码, 原文地址 blog.csdn.net

新建 spring-boot 项目

首先从 spring boot 官方下载基础项目,

这个接口必须用 java 17 和 spring boot3.0。

然后导入 https://start.spring.io/
选择对应的版本,下载完之后倒入到 idea,然后在 idea 中运行项目 mvn 命令 mvn spring-boot:run。
项目上线需要关闭,之后使用 Maven 命令将项目打包,执行命令为: mvn clean package -Dmaven.test.skip=true,等待打包结果即可

打包成功后进入 target 目录,cd target
Java 运行 Jar 包的命令为 java -jar xxx.jar
最后就是启动已经生成的 Jar 包,执行命令为 java -jar spring-demo-demo-0.0.1-SNAPSHOT.jar
在根目录下新建 com.xiaozhang.springboot3.HelloController,
引入重要头部
package cn.lanqiao.springboot3.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class HelloController {

@GetMapping("/hello")
@ResponseBody
public String hello() {
    return "hello,xiaozhang";
}

}

使用 Spring Boot 开发 web 应用时,有两个需要注意的配置项:

server.port 表示启动后的端口号,默认是 8080
server.servlet.context-path 项目路径,是构成 url 地址的一部分

如果想要修改这两个参数值,可以在 application.properties 配置文件中修改,示例如下:
server.port=8082
server.servlet.context-path=/xiaozhang/

数据库配置

在进行数据库连接前,首先将相关 jar 包依赖引入到项目中,Spring Boot 针对 JDBC 的使用提供了对应的 Starter 包:spring-boot-starter-jdbc,方便在 Spring Boot 生态中更好的使用 JDBC,演示项目中使用 MySQL 作为数据库,因此项目中也需要引入 MySQL 驱动包,因此在 pom.xml 文件中新增如下配置:

spring boot 热调试
热部署必须使用 mvn spring-boot:run

<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
			<scope>runtime</scope>
			<optional>true</optional>
		</dependency>
<dependency>





    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.19</version>
</dependency>
## 数据库配置信息

**

为了能够连接上数据库并进行操作,在新增依赖后,我们也需要对数据库的基本信息进行配置,比如数据库地址、账号、密码等信息,这些配置依然是在 application.properties 文件中增加,配置如下:
---
# 数据源基本配置

spring.datasource.url=jdbc:mysql://localhost:3306/spring?useUnicode=true&characterEncoding=utf8&autoReconnect=true&useSSL=false
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.username=root
#密码为空
spring.datasource.password=12345678

mybatis 整合 - springboot-starter

<!-- 引入 MyBatis 场景启动器,包含其自动配置类及 MyBatis 相关依赖 -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>3.0.0</version>
        </dependency>

整合玩 mybatis 就要创建 entity 文件夹里面是 User 类这个是实体类对应数据库,
在新建一个 Dao 文件夹,里面是 UserDao 接口类

/**
 * @author zyh
 * MyBatis
 */
public interface UserDao
{
    /**
     * 查询,返回数据
     *
     */
   List<User> findAllUsers();
    /**
     * 添加
     */
    int insertUser(User User);
    int updUser(User User);
    int delUser(Integer id);
}

处理文件上传以及路径回显

上传文件
Application.properties 中配置上传文件默认大小
和默认请求大小

spring.servlet.multipart.max-file-size=30MB
spring.servlet.multipart.max-request-size=30MB

新建文件上传页面
在 static 目录中新建 upload-test.html,上传页面代码如下:

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title>Spring Boot 文件上传测试</title>
</head>
<body>
<form action="/upload" method="post" enctype="multipart/form-data">
    <input type="file"  />
    <input type="submit" value="提交" />
</form>
</body>
</html>

新建 config 文件夹
写一个 SpringBootWebMvcConfigurer 类继承 WebMvcConfigurer

package cn.xiaozhang.springboot3.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class SpringBootWebMvcConfigurer implements WebMvcConfigurer {
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //registry.addResourceHandler("/files/**").addResourceLocations("file:D:\\upload\\");
        registry.addResourceHandler("/files/**").addResourceLocations("file:/Users/zyh/Downloads/springboot3/upload/");
    }
}

这里要注意后面的上传文件夹路径,
踩坑了,macos 文件路径不同
,在终端中,pwd 查看了当前路径,
然后才找到 upload 放到哪,后面还要加个 / 不然会到项目页面。
Controller 文件夹中也要写 UploadController 类
然后一样的 path 路径保持一致。

package cn.xiaozhang.springboot3.HelloControllor;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

@Controller
public class UploadController {

    private final static String FILE_UPLOAD_PATH = "/Users/zyh/Downloads/springboot3/upload/";

    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @ResponseBody
    public String upload(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return "上传失败";
        }
        String fileName = file.getOriginalFilename();
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        //生成文件名称通用方法
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
        Random r = new Random();
        StringBuilder tempName = new StringBuilder();
        tempName.append(sdf.format(new Date())).append(r.nextInt(100)).append(suffixName);
        String newFileName = tempName.toString();
        try {
            // 保存文件
            byte[] bytes = file.getBytes();
            Path path = Paths.get(FILE_UPLOAD_PATH + newFileName);
            Files.write(path, bytes);

        } catch (IOException e) {
            e.printStackTrace();
        }
        return "上传成功,图片地址为:/files/" + newFileName;
    }
}