Swagger2 在spring mvc 中生成api接口 和文件的上传、 excel的解析

Swagger2 在spring mvc 中生成api接口
在项目的config 目录下
package com.sms.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableWebMvc
@EnableSwagger2
public class Swagger2Config {

    @Bean
    public Docket createSwagger(){
        //文档类型
        return new Docket(DocumentationType.SWAGGER_2)
                //文档信息
                .apiInfo(apiInfo()).select()
                //扫描指定包中的swagger注解
                .apis(RequestHandlerSelectors.basePackage("com.sms.controller"))
                //扫描所有有注解的api,用这种方式更灵活
                //.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                //可以任意访问
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("基础平台 RESTful APIs")
                .description("基础平台 RESTful 风格的接口文档,内容详细,极大的减少了前后端的沟通成本,同时确保代码与文档保持高度一致,极大的减少维护文档的时间。")
                .termsOfServiceUrl("http://www.studentmanger.com")
                .version("1.0.0")
                .build();
    }


}

在controller 目录下

文件上传 fileController.java

package com.sms.controller;
import com.google.common.collect.Maps;

import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.fastjson.JSONObject;
import com.sms.bean.StudentBean;
import com.sms.service.StudentService;
import com.sms.util.CheckUtil;
import com.sms.util.ExcelListener;
import com.sms.util.ReadExcel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author chenlin
 */
@RequestMapping("/file")
@Controller
@Api
@CrossOrigin("*")
public class fileController extends AnalysisEventListener<StudentBean> {

    @Autowired
    private StudentService studentService;

    List<StudentBean> studentBeans =new ArrayList<>();

    //将不合法的学生信息存储到数组中
    List<StudentBean> studentBeanList =new ArrayList<>();
    //将合法的数据存储
    List<StudentBean> studentBeanList1 = new ArrayList<>();



    @ApiOperation("上传文件到C盘的Excel文件夹")
    @PostMapping("/upload")
    @ResponseBody
    public String upload(@RequestParam("file") MultipartFile file)  {
       /* try {
            InputStream inputStream = file.getInputStream();
            //读取Excel信息
            ExcelReader excelReader = new ExcelReader(inputStream, ExcelTypeEnum.XLSX,null,new ExcelListener());
            Sheet sheet = new Sheet(1, 1, StudentBean.class);
            excelReader.read(sheet);
        } catch (IOException e) {
            return "读取数据失败";
        }*/
        //将文件传到C盘的Excel文件夹下
        try {
            //获取文件名称
            String filename = file.getOriginalFilename();
            String savePath="C:\\Excel\\"+filename;
            //文件存储路径
            file.transferTo(new File(savePath));
        } catch (IOException e) {
            return JSONObject.toJSONString("上传失败");
        }

        return JSONObject.toJSONString("上传成功");
    }

excel 表的下载


    @ApiOperation("学生信息表.xlsx模板下载")
    @RequestMapping(value="/downloadEntity",method = RequestMethod.GET)
    @ResponseBody
    public String downloadFile(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //获取输出流对象
        ServletOutputStream out = response.getOutputStream();
        //设置内容类型
        response.setContentType("multipart/form-data");
        //编码
        response.setCharacterEncoding("utf-8");
        //随机文件名
        String fileName = new String(("UserInfo " + new SimpleDateFormat("yyyy-MM-dd").format(new Date()))
                .getBytes(), "UTF-8");
        //下载文件名
        response.setHeader("Content-disposition", "attachment;filename="+fileName+".xlsx");
        //写出excel文件
        ExcelWriter writer = new ExcelWriter(out, ExcelTypeEnum.XLSX, true);

        Sheet sheet1 = new Sheet(1, 0,StudentBean.class);
        sheet1.setSheetName("第一个sheet");
        //写出的对象集合数据
        StudentBean studentBean = new StudentBean();

        studentBean.setChabanTime(new Date());
        studentBean.setStudentId(2011101001);
        studentBean.setStudentName("武大狼");
        studentBean.setStudentPassword("123456");
        studentBean.setStudentSex(1);
        studentBean.setStudentTel(13121210001L);
        studentBean.setStudentQQ(781536077L);
        studentBean.setStudentIDCard("230701195601051002");
        studentBean.setStudentEmail("13444410546@qq.com");
        studentBean.setStudentAddress("成都高新区");
        studentBean.setStudentRemarks("-");
        studentBean.setProfessional("UI");
        studentBean.setDiploma("本科");
        studentBean.setCounselor("黄老师");
        //添加到集合里面
        List<StudentBean> studentBeans = new ArrayList<>();
        studentBeans.add(studentBean);
        writer.write(studentBeans,sheet1);
        writer.finish();
        out.flush();

        return JSONObject.toJSONString("正在下载文件");
    }

读取excel

 @ApiOperation("确认读取Excel信息,并存入到数据库中")
    @PostMapping("/confirmDataToMysql")
    @ResponseBody
    public String confirmParseExcelToMysql(@RequestParam("confirm") String confirm,@RequestParam String token,@RequestParam String fileName){
        System.out.println(confirm+"    ~~~~~~~~   "+token+"   --------     "+fileName);
        String msg = "";
       if(confirm!=null && confirm !="" && confirm.equals("confirm")){
           //读取Excel
           boolean b = ReadExcel.getExcelInfo(fileName);
           if (b){
               //获取读取成功的数据
               if(studentBeanList1!=null){
                   //讲读取到的数据存储到数据库中
                   if (studentBeanList==null){
                       boolean b1 =true; //studentService.addStudents(studentBeanList1);
                       if(b1){
                           msg = "读取Excel成功,成功存入数据库";
                       }
                       System.out.println("批量添加学生成功");
                   }
               }

           }else {
               msg = "读取Excel失败";
           }
       }
        return JSONObject.toJSONString(msg);
    }



    @Override
    public void invoke(StudentBean studentBean, AnalysisContext analysisContext) {
        //System.out.println(studentBean+"------------------------------------------------");
        studentBeans.add(studentBean);
    }
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        System.out.println("读取完毕:------------"+studentBeans);
        System.out.println("合法的数据:"+studentBeanList1);
        System.out.println("不合法的数据:"+studentBeanList);
        /*if (studentBeanList==null && studentBeanList1!=null ){
            boolean b = studentService.addStudents(studentBeanList1);
            System.out.println("批量添加学生成功");
        }*/
        System.out.println("doAfterAllAnalysed");
        Integer totalCount = analysisContext.getTotalCount();
        System.out.println("总行数: "+totalCount);

    }

ReadExcel 工具类 在util包下 ReadExcel.java

package com.sms.util;

import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.sms.bean.StudentBean;
import com.sms.controller.fileController;
import org.apache.poi.EmptyFileException;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

@Component
public class ReadExcel {


    public static boolean getExcelInfo(String fileName)  {

        System.out.println("进入到ReadExcel中");
        String path="C:\\Excel";
        File file = new File(path);
        if (!file.exists()){
            boolean b = file.mkdirs();//如果Excel不存在就创建此目录
        }

        //默认路径
        String oldPath="C:\\Excel\\student-excel.xlsx";
        //填写的路径
        /*if (fileName!=null&&fileName!=""){
            //如果获取的文件名不为空
            File file1 = new File(path, fileName);
            if (!file1.exists()){
                try {
                    file1.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }*/
        oldPath=path+"\\"+fileName;
        System.out.println(oldPath);
        //获取指定目录下的Excel
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(oldPath);
            //读取Excel信息
            ExcelReader excelReader = new ExcelReader(fileInputStream,ExcelTypeEnum.XLSX,null,new fileController());
            Sheet sheet = new Sheet(1, 1, StudentBean.class);
            excelReader.read(sheet);
            System.out.println("读取sheet");
            return true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (EmptyFileException e){
            e.printStackTrace();
        } catch (Exception e){
            e.printStackTrace();
        }
        return false;
    }




}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Swagger是一款流行的API设计工具,它可以帮助我们更轻松地设计、构建和测试APISwagger2是Swagger的一个版本,它可以生成API接口文档,这样我们就可以更清晰地了解API的使用方法。 下面是使用Swagger2生成API接口文档的步骤: 1. 在项目添加Swagger2依赖 在Maven项目,可以在pom.xml文件添加以下依赖: ``` <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.9.2</version> </dependency> ``` 2. 配置Swagger2 在Spring Boot项目,可以在application.properties或application.yml文件添加以下配置: ``` # Swagger2配置 swagger2.enabled=true # 启用Swagger2 swagger2.title=API接口文档 # 文档标题 swagger2.description=API接口文档 # 文档描述 swagger2.version=1.0 # 文档版本 swagger2.basePackage=com.example.demo # 扫描的包路径 ``` 3. 编写API接口Spring Boot项目,可以使用Spring MVC的注解来编写API接口,例如: ``` @RestController @RequestMapping("/api") @Api(tags = "用户管理") public class UserController { @GetMapping("/users") @ApiOperation("获取用户列表") public List<User> getUsers() { // TODO: 查询用户列表 return null; } @GetMapping("/users/{id}") @ApiOperation("根据ID获取用户") @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long") public User getUserById(@PathVariable Long id) { // TODO: 根据ID查询用户 return null; } @PostMapping("/users") @ApiOperation("创建用户") @ApiImplicitParam(name = "user", value = "用户信息", required = true, dataType = "User") public User createUser(@RequestBody User user) { // TODO: 创建用户 return null; } @PutMapping("/users/{id}") @ApiOperation("更新用户") @ApiImplicitParams({ @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long"), @ApiImplicitParam(name = "user", value = "用户信息", required = true, dataType = "User") }) public User updateUser(@PathVariable Long id, @RequestBody User user) { // TODO: 更新用户 return null; } @DeleteMapping("/users/{id}") @ApiOperation("删除用户") @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long") public void deleteUser(@PathVariable Long id) { // TODO: 删除用户 } } ``` 4. 访问Swagger2文档 在启动Spring Boot应用程序后,可以在浏览器访问以下URL以查看Swagger2生成API接口文档:http://localhost:8080/swagger-ui.html 在Swagger2的文档页面,可以查看接口的详细信息,包括请求和响应的参数、请求方式、请求路径等。同时,我们也可以在页面测试API接口

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值