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;
}
}