一个导出指定包下 spring Controller excel清单的例子(包括包名、类名、方法名、访问路径)
来源:互联网 发布:香蕉tv网络电视下载 编辑:程序博客网 时间:2024/04/26 20:20
导出指定包下 spring Controller excel清单的例子(包括包名、类名、方法名、访问路径)
一:首先大体思路是:
1>.获得包下(包含子包下所有Controller)
2>遍历每个Controller类提取注解如:
@RequestMapping(value = "/projectInfo/preheatingFlow", method = RequestMethod.PUT, produces = {"application/json",
"application/xml"})
3>获得注解中的注释内容,这里我用自定义注解类来实现“”
自定义注解类:
import java.lang.annotation.Documented;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;import org.springframework.web.bind.annotation.Mapping;/** * * 用于提供api注释 * <功能详细描述> * * @author liubeihua * @version [版本号, 2016年1月13日] */@Target({ElementType.METHOD, ElementType.TYPE})@Retention(RetentionPolicy.RUNTIME)@Documented@Mappingpublic @interface ApiExplain{ /** * 描述 * @return */ String description() default ""; String other() default ""; String value() default "";}
二:所有代码
<span style="font-size:12px;">GenerateApi</span>
import java.io.File;import java.io.IOException;import java.lang.annotation.Annotation;import java.lang.reflect.Method;import java.net.URL;import java.util.ArrayList;import java.util.Arrays;import java.util.Collections;import java.util.List;import org.apache.shiro.authz.annotation.RequiresRoles;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import com.dimeng.framework.utils.ExcelUtil;/** * * 生成平台接口api清单excel * url ,method,controler,package * * @author liubeihua * @version [版本号, 2016年1月13日] */public class GenerateApi{ /** * 是否不执行 true 为不执行生成api代码 */ private static boolean isNotExe = false; /** * api 实体 */ private static List<ApiEntity> list = new ArrayList(); /** * 获得对应包下的类名称(自动遍历子包) * <功能详细描述> * @param packageName * @return */ public static List<String> getClassName(String packageName) { ClassLoader loader = Thread.currentThread().getContextClassLoader(); String packagePath = packageName.replace(".", "/"); //加载包下的所有资源 URL url = loader.getResource(packagePath); List<String> fileNames = null; if (url != null) { String type = url.getProtocol(); if (type.equals("file")) { fileNames = getClassName(url.getPath(), null); } } return fileNames; } /** * 根据资源路径返回 class 路径 * <功能详细描述> * @param filePath * @param className * @return */ private static List<String> getClassName(String filePath, List<String> className) { List<String> myClassName = new ArrayList<String>(); File file = new File(filePath); File[] childFiles = file.listFiles(); for (File childFile : childFiles) { if (childFile.isDirectory()) { myClassName.addAll(getClassName(childFile.getPath(), myClassName)); } else { String childFilePath = childFile.getPath(); childFilePath = childFilePath.substring(childFilePath.indexOf("\\classes") + 9, childFilePath.lastIndexOf(".")); childFilePath = childFilePath.replace("\\", "."); myClassName.add(childFilePath); } } return myClassName; } /** * 执行生成平台API文档 * <功能详细描述> */ public static void exe() { //如果不执行就退出 if(isNotExe) return; String packageName = "com.dimeng.platform.controller"; System.out.println("开始生成api........................"); List<String> classNames = getClassName(packageName); for (String className : classNames) { System.out.println("类:" + className + " 开始========================="); Class<?> t = null; String classStr = null; String methodStr = null; try { t = Class.forName(className); //请求配置 Class<RequestMapping> annClass = org.springframework.web.bind.annotation.RequestMapping.class; //api 解释 Class<ApiExplain> annApiExplain = com.sinky.api.ApiExplain.class; //权限 Class<RequiresRoles> annRequiresRoles = org.apache.shiro.authz.annotation.RequiresRoles.class; //请求 Annotation annotationClass = t.getAnnotation(annClass); //api类注释 Annotation annotationClassDescription = t.getAnnotation(annApiExplain); classStr = getAnnValues(annotationClass); if (null == classStr) continue; System.out.println("类注解:" + classStr); Method[] methods = t.getMethods(); for (Method m : methods) { methodStr = getAnnValues(m.getAnnotation(annClass), annotationClass, m.getName(), className, m.getAnnotation(annApiExplain), annotationClassDescription, m.getAnnotation(annRequiresRoles) ); if (null == methodStr) continue; System.out.println("方法:" + m.getName() + " " + methodStr); } } catch (ClassNotFoundException e) { e.printStackTrace(); } System.out.println("类:" + className + " 结束========================="); } System.out.println("完成生成api........................"); printApi(); } /** * 打印清单,并生成EXCLE api。 * */ private static void printApi() { List<Object[]> exlList = new ArrayList<Object[]>(); System.out.println(); System.out.println(); System.out.println(); System.out.println("============================"); System.out.println("===================================================================================================================="); Object[] objs = new Object[]{ "包名","类说明","类名称","方法说明","方法名称","restful类型","请求路径","权限码" }; //按包名排序 Collections.sort(list); exlList.add(objs); for (ApiEntity api : list) { System.out.println(api.toString()); exlList.add(api.toObjs()); } System.out.println("================================================================================================================================================================"); //将数据转换成list try { //如果文件存在就删除 File file = new File("F:/api/api.xls"); if(file.exists()) { file.delete(); } //导出接口清单 ExcelUtil.exportExcel(exlList, "F:/api/api.xls"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * 获得注解值 org.springframework.web.bind.annotation.RequestMapping * <功能详细描述> * @param ann 方法RequestMapping注解 * @param classRequestMapp 类RequestMapping注解 * @param methodName 方法名称 * @param className 类全名称(含路径) * @param apiExplainAnn api注释注解 * @param classExplainAnn class注释注解 * @return */ private static String getAnnValues(Annotation ann, Annotation classRequestMapp, String methodName, String className, Annotation apiExplainAnn, Annotation classExplainAnn,Annotation annRequiresRoles) { String str = null; if (null == ann) return str; String[] classTemps = className.split("\\."); //包名 String packageName = classTemps[classTemps.length - 2]; //类名 String classSimpleName = classTemps[classTemps.length - 1]; //方法上的 RequestMapping注解 RequestMapping rmapp = (RequestMapping)ann; //类上的 RequestMapping注解 RequestMapping classMapp = (RequestMapping)classRequestMapp; //api注释方法 ApiExplain apiEx = (ApiExplain)apiExplainAnn; //api类注释 ApiExplain apiClassEx = (ApiExplain)classExplainAnn; //角色权限 RequiresRoles apiRequiresRolesEx = (RequiresRoles)annRequiresRoles; String apiExplain = ""; String apiExplainClass = ""; //接口API访问的URL String url = ""; //方法的权限角色 String [] roles = null; if (classMapp.value().length > 0) { url = classMapp.value()[0]; } String[] values = rmapp.value(); String value = ""; if (values != null && values.length > 0) { value = values[0]; url += value; } RequestMethod[] rms = rmapp.method(); String method = ""; if (rms != null && rms.length > 0) { method = rms[0].name(); } if (null != apiEx) { apiExplain = apiEx.value(); } if (null != apiClassEx) { apiExplainClass = apiClassEx.value(); } if(null != apiRequiresRolesEx) { roles = apiRequiresRolesEx.value(); } ApiEntity apiEntity = new ApiEntity(); apiEntity.setPackageStr(packageName); apiEntity.setClassStr(classSimpleName); apiEntity.setMethodStr(methodName); apiEntity.setUrlStr(url); apiEntity.setMethodType(method); apiEntity.setApiExplain(apiExplain); apiEntity.setClassExplain(apiExplainClass); apiEntity.setRoleCode(roles); list.add(apiEntity); return " value:" + value + " method:" + method; } /** * 获得注解打印值 * * @param ann 注解 * @return */ private static String getAnnValues(Annotation ann) { String str = null; if (null == ann) return str; RequestMapping rmapp = (RequestMapping)ann; String[] values = rmapp.value(); String value = ""; if (values != null && values.length > 0) { value = values[0]; } RequestMethod[] rms = rmapp.method(); String method = ""; if (rms != null && rms.length > 0) { method = rms[0].name(); } return " value:" + value + " method:" + method; }}</span>ApiEntity
import java.util.ArrayList;import java.util.Arrays;import java.util.List;/** * * Api实体 * 描述API的实体对象,主要包括接口URL,接口名称等 * * * @author liubeihua * @version [版本号, 2016年1月13日] */public class ApiEntity implements Comparable<ApiEntity>{ /** * 类名 */ private String classStr; /** * 包名 */ private String packageStr; /** * 请求方法 */ private String methodStr; /** * 请求url */ private String urlStr; /** * 请求类型 put,delete,post,get */ private String methodType; /** * api方法注释 */ private String apiExplain; /** * api类注释 */ private String classExplain; /** * 接口角色码 */ private String[] roleCode; /** * 接口角色码,号分开 */ private String roleCodes; public String getClassStr() { return classStr; } public void setClassStr(String classStr) { this.classStr = classStr; } public String getPackageStr() { return packageStr; } public void setPackageStr(String packageStr) { this.packageStr = packageStr; } public String getMethodStr() { return methodStr; } public void setMethodStr(String methodStr) { this.methodStr = methodStr; } public String getUrlStr() { return urlStr; } public void setUrlStr(String urlStr) { this.urlStr = urlStr; } public String getMethodType() { return methodType; } public void setMethodType(String methodType) { this.methodType = methodType; } public String getApiExplain() { return apiExplain; } public void setApiExplain(String apiExplain) { this.apiExplain = apiExplain; } public String getClassExplain() { return classExplain; } public void setClassExplain(String classExplain) { this.classExplain = classExplain; } public String toString() { return " "+packageStr+" "+classStr+" "+methodStr+" "+methodType+" "+urlStr; } public String[] getRoleCode() { return roleCode; } public void setRoleCode(String[] roleCode) { this.roleCode = roleCode; } public String getRoleCodes() { return roleCodes; } public void setRoleCodes(String roleCodes) { this.roleCodes = roleCodes; } public Object[] toObjs() { String roles = ""; if(null != roleCode) { roles = Arrays.toString(roleCode); } Object[] objs = new Object[]{ packageStr,classExplain,classStr,apiExplain,methodStr,methodType,urlStr,roles }; return objs; } @Override public int compareTo(ApiEntity par) { int rInt = 0; String parPackge = par.getPackageStr(); String packgeStr = this.getPackageStr(); if(parPackge!=null && packgeStr!=null) { rInt = packgeStr.compareTo(parPackge); } return rInt; }}</span>
依赖导出excel工具类:ExcelUtil
/*** Eclipse Class Decompiler plugin, copyright (c) 2012 Chao Chen (cnfree2000@hotmail.com) ***/import java.io.BufferedInputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.OutputStream;import java.sql.Timestamp;import java.text.DecimalFormat;import java.text.SimpleDateFormat;import java.util.ArrayList;import java.util.Arrays;import java.util.List;import javax.servlet.http.HttpServletResponse;import org.apache.poi.hssf.usermodel.HSSFCell;import org.apache.poi.hssf.usermodel.HSSFDateUtil;import org.apache.poi.hssf.usermodel.HSSFRow;import org.apache.poi.hssf.usermodel.HSSFSheet;import org.apache.poi.hssf.usermodel.HSSFWorkbook;import org.apache.poi.poifs.filesystem.POIFSFileSystem;import org.apache.poi.ss.usermodel.Cell;import org.apache.poi.ss.usermodel.CellStyle;import org.apache.poi.ss.usermodel.Font;import org.apache.poi.ss.usermodel.Row;import org.apache.poi.ss.usermodel.Sheet;import org.apache.poi.ss.usermodel.Workbook;public class ExcelUtil{ public static String[][] readData(File file, int ignoreRows) throws FileNotFoundException, IOException { List result = new ArrayList(); int rowSize = 0; BufferedInputStream in = new BufferedInputStream(new FileInputStream(file)); POIFSFileSystem fs = new POIFSFileSystem(in); HSSFWorkbook wb = new HSSFWorkbook(fs); HSSFCell cell = null; for (int sheetIndex = 0; sheetIndex < wb.getNumberOfSheets(); ++sheetIndex) { HSSFSheet st = wb.getSheetAt(sheetIndex); for (int rowIndex = ignoreRows; rowIndex <= st.getLastRowNum(); ++rowIndex) { HSSFRow row = st.getRow(rowIndex); if (row == null) { continue; } int tempRowSize = row.getLastCellNum() + 1; if (tempRowSize > rowSize) { rowSize = tempRowSize; } String[] values = new String[rowSize]; Arrays.fill(values, ""); boolean hasValue = false; for (short columnIndex = 0; columnIndex <= row.getLastCellNum(); columnIndex = (short)(columnIndex + 1)) { String value = ""; cell = row.getCell(columnIndex); if (cell != null) { switch (cell.getCellType()) { case 1: value = cell.getStringCellValue(); break; case 0: if (HSSFDateUtil.isCellDateFormatted(cell)) { java.util.Date date = cell.getDateCellValue(); if (date != null) { value = new SimpleDateFormat("yyyy-MM-dd").format(date); } else { value = ""; } } else { value = new DecimalFormat("##########0.00").format(cell.getNumericCellValue()); } break; case 2: if (!(cell.getStringCellValue().equals(""))) { value = cell.getStringCellValue(); } else { value = cell.getNumericCellValue(); } break; case 3: break; case 5: value = ""; break; case 4: value = (cell.getBooleanCellValue()) ? "Y" : "N"; break; default: value = ""; } } values[columnIndex] = value.trim(); hasValue = true; } if (!(hasValue)) continue; result.add(values); } } in.close(); String[][] returnArray = new String[result.size()][rowSize]; for (int i = 0; i < returnArray.length; ++i) { returnArray[i] = ((String[])result.get(i)); } return returnArray; } public static void exportExcel(List<Object[]> data, String fileName) throws IOException { HSSFWorkbook wb = new HSSFWorkbook(); Sheet sheet = wb.createSheet(); Font font0 = createFonts(wb, 700, "宋体", false, 200); for (int i = 0; i < data.size(); ++i) { Row rowData = sheet.createRow(i); int j = 0; for (Object value : (Object[])data.get(i)) { createCell(wb, rowData, j++, value, (i == 0) ? font0 : null); } } FileOutputStream fos = new FileOutputStream(fileName); wb.write(fos); fos.flush(); fos.close(); } private static void exportExcel(List<Object[]> data, OutputStream os) throws IOException { HSSFWorkbook wb = new HSSFWorkbook(); Sheet sheet = wb.createSheet(); Font font0 = createFonts(wb, 700, "宋体", false, 200); for (int i = 0; i < data.size(); ++i) { Row rowData = sheet.createRow(i); int j = 0; for (Object value : (Object[])data.get(i)) { createCell(wb, rowData, j++, value, (i == 0) ? font0 : null); } } wb.write(os); os.flush(); } public static void downloadExcel(String filename, HttpServletResponse response, List<Object[]> data) { OutputStream os = null; try { response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes("GBK"), "ISO-8859-1")); response.setContentType("application/octet-stream"); os = response.getOutputStream(); exportExcel(data, os); } catch (Exception e) { e.printStackTrace(); } finally { try { if (os != null) os.close(); } catch (Exception e) { e.printStackTrace(); } } } private static void createStringCell(Workbook wb, Row row, int column, String value, Font font) { if ((value == null) || (value.equals("null"))) value = ""; if (value.matches("\\d+\\-\\d+\\-\\d+ \\d+:\\d+:\\d+\\.0")) value = value.substring(0, value.length() - 2); Cell cell = row.createCell(column); cell.setCellValue(value); if (font == null) return; CellStyle cellStyle = wb.createCellStyle(); cellStyle.setFont(font); cellStyle.setFillBackgroundColor(60); cellStyle.setFillForegroundColor(9); cell.setCellStyle(cellStyle); } private static void createCell(Workbook wb, Row row, int column, Object value, Font font) { if (value instanceof Long) { Cell cell = row.createCell(column); if (value == null) return; cell.setCellValue(((Long)value).doubleValue()); } else if (value instanceof Integer) { Cell cell = row.createCell(column); if (value == null) return; cell.setCellValue(((Integer)value).doubleValue()); } else if (value instanceof Float) { Cell cell = row.createCell(column); if (value == null) return; cell.setCellValue(((Float)value).doubleValue()); } else if (value instanceof Boolean) { Cell cell = row.createCell(column); cell.setCellValue(((Boolean)value).booleanValue()); } else { createStringCell(wb, row, column, value, font); } } private static Font createFonts(Workbook wb, short bold, String fontName, boolean isItalic, short hight) { Font font = wb.createFont(); font.setFontName(fontName); font.setBoldweight(bold); font.setItalic(isItalic); font.setFontHeight(hight); return font; } }
导出后清单的例子:(权限码是后续清单中所添加的)
0 0
- 一个导出指定包下 spring Controller excel清单的例子(包括包名、类名、方法名、访问路径)
- Android Studio如何更换包名(包括代码路径名和项目包名)
- phonegap创建工程 生成指定的包名 类名 应用名
- 常用软件的包名和类名
- java的类名、文件名、包名
- Applet 类路径问题(含有包名的时候)
- Android通过包名,查找包下面的指定类的类名
- 启动apk的常用方法(包括只知道包名的启动方法)
- 启动apk的常用方法(包括只知道包名的启动方法)
- 启动apk的常用方法(包括只知道包名的启动方法)
- android 打开指定包名的apk
- android杀掉指定包名的应用程序
- 从一个应用中启动其他的apk(不知道包名和类名)
- maven package 指定包名
- maven package 指定包名
- Java语言中,包名、类名、接口名、方法名、变量名,以及常量名的命名有何规范的命名习惯
- Java语言中,包名、类名、接口名、方法名、变量名,以及常量名的命名有何规范的命名习惯
- 获取指定路径下的文件夹名
- HibernateUtil公共类的使用------java操作数据库(1)
- python tkinter实现简单计算器
- hdu2191(多重背包问题)
- AlertDialog(自定义对话框)示例
- Matlab Compiler或mcc的使用
- 一个导出指定包下 spring Controller excel清单的例子(包括包名、类名、方法名、访问路径)
- HDU 1213 How Many Tables
- 258. Add Digits
- 通过Hexo在GitHub搭站全记录
- java流与文件——对象流和序列化
- 日常开发——KVO的几个坑
- mongoDB
- Unity: Now You're Thinking With Components
- JdbcTemplateUtil公共类的使用-------java操作数据库(2)