spring boot 开发接口

新建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" name="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;
    }
}
  • 9
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值