day11 SpringBoot案例2

  1. 用什么注解可以快速获取日志对象?

    @slf4j
    mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

  2. 文件上传前端表单必须具备哪三个要素?

    上传文件的原始form表单,要求表单必须具备以下三点(上传文件页面三要素):

    • 表单必须有 file 域,用于选择要上传的文件。

    • 表单提交方式必须为 POST。

    • 表单的编码类型enctype必须要设置为 multipart/form-data。

  3. 文件上传功能开发时,后台用什么类型的参数来接收文件?

    我们要想接收上传上来的文件,需要使用Spring给我们提供的一个,专门接收文件的API : MultipartFile。

    MultipartFile 常见方法:

    getOriginalFilename():获取原始文件名 ​ getContentType():获取文件的类型 ​ getInputStream():获取文件的输入流 ​ transferTo(File dest) :将上传的文件保存到目标文件中(Mac中测试有问题,可以使用流获取数据拷贝方式) ​ getBytes():获取文件的字节数组

  4. 请说说你的图片存储方案是怎样的?

    本地存储

    • 选择文件,进行图片上传,将图片文件上传到服务器存储起来,然后返回图片访问的URL。

    • 当点击保存时,除了页面的基本表单数据需要提交到服务端,图片访问的URL,也需要提交到服务端。

    直接存储在服务器的磁盘目录中,存在以下缺点:

    • 不安全:磁盘如果损坏,所有的文件就会丢失。

    • 容量有限:如果存储大量的图片,磁盘空间有限(磁盘不可能无限制扩容)。

    • 无法直接访问

    为了解决上述问题呢,一般有两种解决方案:

    • 自己搭建文件存储系统,如:fastDFS

    • 自己搭建对象存储服务,如:MinIO

    • 使用现成的云服务,如:阿里云,腾讯云,华为云

    阿里云OSS

    参照官方提供的SDK,改造一下,即可实现文件上传功能。

    1). pom.xml

    <dependency>
        <groupId>com.aliyun.oss</groupId>
        <artifactId>aliyun-sdk-oss</artifactId>
        <version>3.15.0</version>
    </dependency>

    测试文件上传

    import org.junit.jupiter.api.Test;
    import com.aliyun.oss.ClientException;
    import com.aliyun.oss.OSS;
    import com.aliyun.oss.OSSClientBuilder;
    import com.aliyun.oss.OSSException;
    import java.io.FileInputStream;
    import java.io.InputStream;
    ​
    public class AliOssTest {
    ​
        @Test
        public void testOss(){
            // Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
            String endpoint = "换成自己的";
            // 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
            String accessKeyId = "换成自己的";
            String accessKeySecret = "换成自己的";
            // 填写Bucket名称,例如examplebucket。
            String bucketName = "换成自己的";
            // 填写Object完整路径,完整路径中不能包含Bucket名称,例如exampledir/exampleobject.txt。
            String objectName = "0001.jpg";
            // 填写本地文件的完整路径,例如D:\\localpath\\examplefile.txt。
            // 如果未指定本地路径,则默认从示例程序所属项目对应本地路径中上传文件流。
            String filePath= "C:\\Users\\Administrator\\Pictures\\Saved Pictures\\10.jpg";
    ​
            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
    ​
            try {
                InputStream inputStream = new FileInputStream(filePath);
                // 创建PutObject请求。
                ossClient.putObject(bucketName, objectName, inputStream);
            } catch (OSSException oe) {
                System.out.println("Caught an OSSException, which means your request made it to OSS, "
                        + "but was rejected with an error response for some reason.");
                System.out.println("Error Message:" + oe.getErrorMessage());
                System.out.println("Error Code:" + oe.getErrorCode());
                System.out.println("Request ID:" + oe.getRequestId());
                System.out.println("Host ID:" + oe.getHostId());
            } catch (Exception ce) {
                System.out.println("Caught an ClientException, which means the client encountered "
                        + "a serious internal problem while trying to communicate with OSS, "
                        + "such as not being able to access the network.");
                System.out.println("Error Message:" + ce.getMessage());
            } finally {
                if (ossClient != null) {
                    ossClient.shutdown();
                }
            }
        }
    }

  5. 请说说你的员工修改是怎么实现的?

    在进行修改员工信息的时候,我们首先先要根据员工的ID查询员工的信息用于页面回显展示,然后用户修改员工数据之后,点击保存按钮,就可以将修改的数据提交到服务端,保存到数据库。 所以呢,分为两部操作:

    • 根据ID查询员工信息

    • 保存修改

    查询回显,就是根据ID查询员工的信息,用于页面回显展示。接下来,我们就需要参考接口文档进行开发:

     

    1). EmpMapper

    //根据ID查询员工信息
    @Select("select * from emp where id = #{id}")
    Emp getById(Integer id);

    2). EmpService / EmpServiceImpl

    EmpService

    /**
    * 根据ID查询员工
    * @param id
    * @return
    */
    Emp getById(Integer id);

    EmpServiceImpl

    @Override
    public Emp getById(Integer id) {
        return empMapper.getById(id);
    }

    3). EmpController

    //根据id查询
    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id){
        Emp emp = empService.getById(id);
        return Result.success(emp);
    }

    4). 测试

    代码编写完毕后,启动服务器,打开Postman发送 GET 请求,请求连接:

     

    保存修改

    当用户修改完数据之后,点击保存按钮,就需要将数据提交到服务端,然后服务端需要将数据保存到数据库中。 具体的执行流程为:

     

    接下来,我们就可以根据接口文档进行功能开发了。

    1). EmpMapper

    EmpMapper接口

    EmpMapper.xml

    2). EmpService / EmpServiceImpl

    EmpService

    /**
    * 更新员工
    * @param emp
    */
    void update(Emp emp);

    EmpServiceImpl

    @Override
    ​
    public void update(Emp emp) {
    ​
     emp.setUpdateTime(LocalDateTime.now()); //更新修改时间为当前时间
     empMapper.update(emp);
    }

    3). EmpController

    //修改
    @PutMapping
    public Result update(@RequestBody Emp emp){
        empService.update(emp);
        return Result.success();
    }

    4). 测试

     5). 联调测试

     

  6. @Value,@ConfigurationProperties 两个注解怎么用的

    @Value 注解通常用于外部配置的属性注入,具体用法为: @Value("${配置文件中的key}")

    @ConfigurationProperties

    1). 定义实体类,用于封装需要注入的属性。

    import lombok.Data;
    import org.springframework.boot.context.properties.ConfigurationProperties;
    import org.springframework.stereotype.Component;
    ​
    @Data
    @Component
    @ConfigurationProperties(prefix = "aliyun.oss") //指定配置文件
    public class AliOSSProperties {
        private String endpoint;
        private String accessKeyId;
        private String accessKeySecret;
        private String bucketName;
    }

    2). 在工具类中,注解注入上述的bean对象,然后调用get方法就可以获取到各个属性

    ​
    import com.aliyun.oss.OSS;
    import com.aliyun.oss.OSSClientBuilder;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.stereotype.Component;
    import org.springframework.web.multipart.MultipartFile;
    import java.io.*;
    import java.time.LocalDateTime;
    import java.time.format.DateTimeFormatter;
    ​
    /**
     * 阿里云 OSS 工具类
     */
    @Component
    public class AliOSSUtils {
    ​
        @Autowired
        private AliOSSProperties aliOSSProperties;
    ​
        /**
         * 实现上传图片到OSS
         */
        public String upload(MultipartFile multipartFile) throws IOException {
            // 获取上传的文件的输入流
            InputStream inputStream = multipartFile.getInputStream();
    ​
            // 避免文件覆盖
            String fileName = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd-HH-mm-ss")) + multipartFile.getOriginalFilename();
    ​
            //上传文件到 OSS
            OSS ossClient = new OSSClientBuilder().build(aliOSSProperties.getEndpoint(), aliOSSProperties.getAccessKeyId(), aliOSSProperties.getAccessKeySecret());
            ossClient.putObject(aliOSSProperties.getBucketName(), fileName, inputStream);
    ​
            //文件访问路径
            String url = aliOSSProperties.getEndpoint().split("//")[0] + "//" + aliOSSProperties.getBucketName() + "." + aliOSSProperties.getEndpoint().split("//")[1] + "/" + fileName;
            // 关闭ossClient
            ossClient.shutdown();
            return url;// 把上传到oss的路径返回
        }
    ​
    }

  7. 配置文件有几种形式,常用的那种

    Value

    yml

    yaml

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值