Jfinal集成swagger的最简单方式,支持response

新建一个Controller命名叫SwaggerController内容如下 

package com.operation.controller;

import com.google.gson.Gson;
import com.ideabobo.swagger.util.StringUtil;
import com.jfinal.core.Controller;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import io.swagger.models.Contact;
import io.swagger.models.Info;
import io.swagger.models.License;
import io.swagger.models.Operation;
import io.swagger.models.Path;
import io.swagger.models.Response;
import io.swagger.models.Scheme;
import io.swagger.models.Swagger;
import io.swagger.models.Tag;
import io.swagger.models.parameters.Parameter;
import io.swagger.models.parameters.PathParameter;

import java.io.File;
import java.io.FileFilter;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.net.JarURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

public class SwaggerController extends Controller {
    //设置需要扫描哪个包里面的类生产api
	public static final String BASE_PACKAGE="com.swaggerTest";
	public void index() {
		render("index.html");
	}

	public void api() {
		Swagger doc = new Swagger();
		Info info = new Info();
		Contact contact = new Contact();
		contact.setEmail("admin@bimfoo.com");
		contact.setName("bimfoo");
		contact.setUrl("http://www.baidu.com");

		info.setDescription("项目接口的总体描述信息");
		License license = new License();
		license.setName("Apache 2.0");
		license.setUrl("http://www.baidu.com");
		info.setLicense(license);
		info.setTitle("运营平台接口");
		info.setTermsOfService("http://www.baidu.com");
		info.setVersion("2.0");
		info.setContact(contact);

		List<Scheme> schemes = new ArrayList<>();
		schemes.add(Scheme.HTTP);
		schemes.add(Scheme.HTTPS);

		Map<String, Path> paths = new HashMap<>();

		Set<Class<?>> classSet = getClassSet(BASE_PACKAGE);
		List<Tag> tags = new ArrayList<>();
		for (Class<?> cls : classSet) {
			if (cls.isAnnotationPresent(Api.class)) {
				Api api = cls.getAnnotation(Api.class);
				String[] apitags = api.tags();
				String apiValue = api.value();

				if (apitags.length > 0) {
					for (String tag : apitags) {
						Tag tagobj = new Tag();
						tagobj.setName(tag);
						tags.add(tagobj);
					}
				} else {
					Tag tagobj = new Tag();
					tagobj.setName(apiValue);
					tags.add(tagobj);
				}

				Method[] methods = cls.getMethods();

				for (Method method : methods) {
					Annotation[] annotations = method.getAnnotations();
					Path path = new Path();

					for (Annotation annotation : annotations) {
						// Class<?> aclass = annotation.annotationType();
						Operation option = new Operation();
						String opvalue = "";
						if (method.isAnnotationPresent(ApiOperation.class)) {
							ApiOperation opertion = method.getAnnotation(ApiOperation.class);
							ArrayList<String> produces = new ArrayList<>();
							String producesStr = opertion.produces();
							produces.add(producesStr);

							opvalue = opertion.value();
							String notes = opertion.notes();
							/*
							 * String consumesStr = opertion.consumes();
							 * String[] ptagsarray = opertion.tags();
							 */
							List<String> ptags = new ArrayList<>();
							ptags.add(apitags[0]);
							/*
							 * if(ptagsarray.length>0){ for(String
							 * tag:ptagsarray){ ptags.add(tag); } }
							 */

							option.setConsumes(new ArrayList<String>());
							option.setDescription(notes);
							option.setSummary(notes);
							option.setTags(ptags);

						}
						List<Parameter> parameters = new ArrayList<>();
						if (method.isAnnotationPresent(ApiImplicitParams.class)) {
							ApiImplicitParams apiImplicitParams = method.getAnnotation(ApiImplicitParams.class);
							ApiImplicitParam[] apiImplicitParamArray = apiImplicitParams.value();

							for (ApiImplicitParam param : apiImplicitParamArray) {
								PathParameter parameter = new PathParameter();
								String in = param.paramType();
								String name = param.name();
								String value = param.value();
								boolean required = param.required();
								String dataType = param.dataType();

								parameter.setType(dataType);
								parameter.setDefaultValue("");
								parameter.setDescription(value);
								parameter.setRequired(required);
								parameter.setIn(in);
								parameter.setName(name);
								parameters.add(parameter);
							}
						}
						option.setParameters(parameters);

						Map<String, Response> responseMap = new HashMap<>();
						if (method.isAnnotationPresent(ApiResponses.class)) {
							ApiResponses responses = method.getAnnotation(ApiResponses.class);
							ApiResponse[] responseArray = responses.value();
							for (ApiResponse response : responseArray) {
								String code = response.code() + "";
								String msg = response.message();
								Response res = new Response();
								res.setDescription(msg);
								responseMap.put(code, res);

							}

						}

						option.setResponses(responseMap);
						path.setGet(option);
						paths.put(opvalue, path);
					}

				}
				doc.setSchemes(schemes);
				doc.setSwagger("2.0");
				doc.setBasePath("");
				doc.setInfo(info);
				doc.setHost("http://localhost");
				doc.setTags(tags);
				doc.setPaths(paths);

			}

		}
		Gson gson = new Gson();
		String json = gson.toJson(doc);
		renderText(json);
	}

	/**
	 * 获取指定包名下所有类
	 *
	 * @param packageName
	 * @return
	 */
	public static Set<Class<?>> getClassSet(String packageName) {
		Set<Class<?>> classSet = new HashSet<Class<?>>();
		try {
			Enumeration<URL> urls = getClassLoader().getResources(packageName.replace(".", "/"));
			while (urls.hasMoreElements()) {
				URL url = urls.nextElement();
				if (url != null) {
					String protocol = url.getProtocol();
					if (protocol.equals("file")) {
						String packagePath = url.getPath().replace("%20", " ");
						addClass(classSet, packagePath, packageName);
					} else if (protocol.equals("jar")) {
						JarURLConnection jarURLConnection = (JarURLConnection) url.openConnection();
						if (jarURLConnection != null) {
							JarFile jarFile = jarURLConnection.getJarFile();
							if (jarFile != null) {
								Enumeration<JarEntry> jarEntries = jarFile.entries();
								while (jarEntries.hasMoreElements()) {
									JarEntry jarEntry = jarEntries.nextElement();
									String jarEntryName = jarEntry.getName();
									if (jarEntryName.endsWith(".class")) {
										String className = jarEntryName.substring(0, jarEntryName.lastIndexOf("."))
												.replaceAll("/", ".");
										doAddClass(classSet, className);
									}
								}
							}
						}
					}
				}
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return classSet;
	}

	/**
	 * 获取类加载器
	 *
	 * @return
	 */
	public static ClassLoader getClassLoader() {
		return Thread.currentThread().getContextClassLoader();
	}

	private static void addClass(Set<Class<?>> classSet, String packagePath, String packageName) {
		File[] files = new File(packagePath).listFiles(new FileFilter() {
			public boolean accept(File file) {
				return (file.isFile() && file.getName().endsWith(".class")) || file.isDirectory();
			}
		});
		for (File file : files) {
			String fileName = file.getName();
			if (file.isFile()) {
				String className = fileName.substring(0, fileName.lastIndexOf("."));
				if (StringUtil.isNotEmpty(packageName)) {
					className = packageName + "." + className;
				}
				doAddClass(classSet, className);
			} else {
				String subPackagePath = fileName;
				if (StringUtil.isNotEmpty(packagePath)) {
					subPackagePath = packagePath + "/" + subPackagePath;
				}
				String subPackageName = fileName;
				if (StringUtil.isNotEmpty(packageName)) {
					subPackageName = packageName + "." + subPackageName;
				}
				addClass(classSet, subPackagePath, subPackageName);
			}
		}
	}

	private static void doAddClass(Set<Class<?>> classSet, String className) {
		Class<?> cls = loadClass(className, false);
		classSet.add(cls);
	}

	/**
	 * 加载类
	 *
	 * @param className
	 * @param isInitialized
	 *            false 代表装载类的时候 不进行初始化工作[不会执行静态代码块]
	 * @return
	 */
	public static Class<?> loadClass(String className, boolean isInitialized) {
		Class<?> cls;
		try {
			cls = Class.forName(className, isInitialized, getClassLoader());
		} catch (ClassNotFoundException e) {
			throw new RuntimeException(e);
		}
		return cls;
	}
}

pom.xml引入<dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>2.2.2</version>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>2.2.2</version>
    </dependency>

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.5</version>
</dependency>

下载你需要的swagger-ui官方下载地址解压后把里面的dist内的文件拷贝到webapp里,然后打开index.html修改里面的url到能访问到我们新建controller的api函数,启动项目跳转到index.html 就可以了.这里就不很死板的说哪儿怎么配,原理就是这样,自己配routes就好了

最后别忘了在需要显示的方法和controller上面写注解像这样

 

@Api(tags="项目相关接口")
public class ProjectAction {
	@ApiOperation(value = "/getProjectById", httpMethod = "GET", 
		    consumes="application/json;charset=UFT-8",produces="application/json;charset=UFT-8",
		    notes = "根据项目id获取项目,更详细的说明")
	@ApiImplicitParams(@ApiImplicitParam(required = true, name = "pid", value = "项目的id",dataType="Long"))
	@ApiResponses({ @ApiResponse(code = 200, message = "Success"),@ApiResponse(code = 400, message = "Invalid Order") })
	public void getProjectById(){
		
	}
	
	@ApiOperation(value = "/getProjectByName", httpMethod = "GET", 
		    consumes="application/json;charset=UFT-8",produces="application/json;charset=UFT-8",
		    notes = "根据项目名称获取项目,更详细的说明")
	@ApiImplicitParams(@ApiImplicitParam(required = true, name = "pname", value = "项目的名称",dataType="String"))
	@ApiResponses({ @ApiResponse(code = 200, message = "Success"),@ApiResponse(code = 400, message = "Invalid Order") })
	public void getProjectByName(){
		
	}
}

 

JFinal是一款基于Java的轻量级Web开发框架,而Shiro是一个强大且易用的Java安全框架。集成JFinal和Shiro可以为你的应用程序提供更好的安全性和权限控制。 要在JFinal集成Shiro,你需要进行以下步骤: 1. 添加Shiro依赖:在你的项目中添加Shiro的依赖,可以通过Maven或者手动下载jar包的方式引入。 2. 创建Shiro配置类:创建一个继承自JFinalJFinalConfig类,并重写configConstant()和configInterceptor()方法。在configConstant()方法中配置Shiro的相关参数,如设置登录页面、未授权页面等。在configInterceptor()方法中添加Shiro的拦截器,用于实现权限控制。 3. 创建ShiroRealm类:创建一个继承自org.apache.shiro.realm.AuthorizingRealm的类,用于实现用户认证和授权逻辑。在该类中,你需要重写doGetAuthenticationInfo()方法用于用户认证,以及重写doGetAuthorizationInfo()方法用于用户授权。 4. 配置ShiroFilter:在JFinal的configRoute()方法中配置ShiroFilter,用于拦截请求并进行权限验证。你可以通过配置URL的匹配规则和相应的权限要求来实现不同页面的权限控制。 5. 配置登录和注销功能:在JFinal的Controller中添加登录和注销的处理逻辑,包括用户登录验证、生成和保存用户的身份信息等。 6. 配置权限注解:使用Shiro的注解来标记需要进行权限验证的方法或类,以实现细粒度的权限控制。 以上是集成JFinal和Shiro的基本步骤,你可以根据具体需求进行更详细的配置和扩展。希望对你有所帮助!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值