本文主要是介绍javalin实现restful接口并集成swagger设置header字段,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
javalin实现restful接口并集成swagger设置header字段
配置依赖
dependencies {implementation fileTree(dir: "lib", include: ['*.jar'])implementation 'cn.hutool:hutool-all:5.3.5'implementation 'io.javalin:javalin-bundle:4.1.1'implementation 'com.alibaba:druid:1.2.6'implementation 'org.mybatis:mybatis:3.5.4'runtimeOnly 'com.oracle:ojdbc6:11.2.0.3'compileOnly 'org.projectlombok:lombok:1.18.12'annotationProcessor 'org.projectlombok:lombok:1.18.12'//implementation 'io.springfox:springfox-swagger-ui:3.0.0'//implementation 'io.springfox:springfox-swagger2:3.0.0'}
代码中增加OpenApiPlugin ,增加swagger的支持
package com.soft;import java.util.concurrent.TimeUnit;import org.eclipse.jetty.http.HttpStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;import com.soft.config.HeaderParam;
import com.soft.config.Router;
import com.soft.config.ServerConf;
import com.soft.controller.TestController;
import com.soft.controller.UserController;
import com.soft.event.EventListener;
import com.soft.exception.AppException;
import com.soft.exception.BaseException;
import com.soft.util.CacheUtil;
import com.soft.util.ErrorType;
import com.soft.util.RetResult;import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import io.javalin.Javalin;
import io.javalin.apibuilder.ApiBuilder;
import io.javalin.http.util.NaiveRateLimit;
import io.javalin.plugin.openapi.InitialConfigurationCreator;
import io.javalin.plugin.openapi.OpenApiOptions;
import io.javalin.plugin.openapi.OpenApiPlugin;
import io.javalin.plugin.openapi.ui.ReDocOptions;
import io.javalin.plugin.openapi.ui.SwaggerOptions;
import io.swagger.v3.oas.models.Components;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.security.SecurityScheme;public class AppStart {private static final Logger log = LoggerFactory.getLogger(AppStart.class);public static void main(String[] args) {Javalin app = Javalin.create(config -> {config.registerPlugin(getConfiguredOpenApiPlugin());config.defaultContentType = "application/json";}).start(ServerConf.getVo().getPort());CacheUtil.eventBus.register(new EventListener());beforeHandle(app);afterHandle(app);exceptionHandle(app);app.routes(() -> {ApiBuilder.get(Router.ping, TestController::ping);ApiBuilder.post(Router.verifyPwd, UserController::verifyPwd);});}private static OpenApiPlugin getConfiguredOpenApiPlugin() {// swagger-ui中输入框传入请求头参数验证// controller中每个接口方法中必须增加@OpenApiSecurity注解才能生效InitialConfigurationCreator init = () -> {Components comps = new Components();comps.addSecuritySchemes(HeaderParam.X_APP_ID, buildSecurityScheme(HeaderParam.X_APP_ID)).addSecuritySchemes(HeaderParam.X_APP_KEY, buildSecurityScheme(HeaderParam.X_APP_KEY));return new OpenAPI().info(new Info().version("1.0").description("接口")).components(comps);};OpenApiOptions options = new OpenApiOptions(init).activateAnnotationScanningFor("com.soft.controller").path("/swagger-docs") // endpoint for OpenAPI json.swagger(new SwaggerOptions("/swagger")) // endpoint for swagger-ui.reDoc(new ReDocOptions("/redoc")) // endpoint for redoc.defaultDocumentation(doc -> {
// doc.json("500", ErrorResponse.class);
// doc.json("503", ErrorResponse.class);});return new OpenApiPlugin(options);}private static SecurityScheme buildSecurityScheme(String name) {return new SecurityScheme().type(SecurityScheme.Type.APIKEY).in(SecurityScheme.In.HEADER).name(name);}private static void beforeHandle(Javalin app) {app.before("/*", ctx -> {// throws if rate limit is exceededNaiveRateLimit.requestPerTimeUnit(ctx, ServerConf.getVo().getX_RateLimit_Limit(), TimeUnit.SECONDS);String logid = RandomUtil.randomString(5);ctx.attribute("logid", logid);String ip = ctx.ip();String path = ctx.path();if (path.contains("/test/ping") || path.contains("/swagger")) {return;}String body = ctx.body();String reqid = ctx.header(HeaderParam.X_CTG_Request_ID);log.info("reqid:{}|{}|REQ ip:{},path:{},body:{}", reqid, logid, ip, path, body);String x_app_id = ctx.req.getHeader(HeaderParam.X_APP_ID);String x_app_key = ctx.req.getHeader(HeaderParam.X_APP_KEY);if (StrUtil.isBlank(x_app_id) || StrUtil.isBlank(x_app_key)) {String msg = "请求头中 X-APP-ID, X-APP-KEY 必须传送";throw new AppException(ErrorType.BadReq, msg);}if (!StrUtil.equalsIgnoreCase(x_app_id, ServerConf.getVo().getX_APP_ID())) {String msg = "请求头中X-APP-ID与服务端配置不同";throw new AppException(ErrorType.BadReq, msg);}if (!StrUtil.equalsIgnoreCase(x_app_key, ServerConf.getVo().getX_APP_KEY())) {String msg = "请求头中X-APP-KEY与服务端配置不同";throw new AppException(ErrorType.BadReq, msg);}});}private static void afterHandle(Javalin app) {app.after("/*", ctx -> {// 2.1.7请求跟踪, 设置与请求头相同的值String reqid = ctx.req.getHeader(HeaderParam.X_CTG_Request_ID);ctx.res.addHeader("X-CTG-Request-ID", reqid);String logid = ctx.attribute("logid");log.info("reqid:{}|{}|RSP status:{} body:{}", reqid, logid, ctx.status(), ctx.resultString());});}private static void exceptionHandle(Javalin app) {
// app.exception(NullPointerException.class, (e, ctx) -> {
// // handle nullpointers here
// log.error("", e);
// ctx.status(HttpStatus.INTERNAL_SERVER_ERROR_500).result("NullPointerException");
// });app.exception(Exception.class, (ex, ctx) -> {RetResult re = null;if (ex instanceof BaseException) {// 自定义异常BaseException e = (BaseException) ex;re = new RetResult(e.getCode(), e.getMessage());} else {re = new RetResult(ErrorType.Fail.getCode(), ex.getMessage());log.error("", ex);}ctx.status(HttpStatus.INTERNAL_SERVER_ERROR_500).json(re);});}
}
package com.soft.controller;import java.util.ArrayList;
import java.util.Date;
import java.util.List;import org.eclipse.jetty.http.HttpStatus;import io.javalin.http.Context;
import io.javalin.plugin.openapi.annotations.HttpMethod;
import io.javalin.plugin.openapi.annotations.OpenApi;
import io.javalin.plugin.openapi.annotations.OpenApiContent;
import io.javalin.plugin.openapi.annotations.OpenApiRequestBody;
import io.javalin.plugin.openapi.annotations.OpenApiResponse;
import io.javalin.plugin.openapi.annotations.OpenApiSecurity;public class UserController {@OpenApi(path = Router.verifyPwd, method = HttpMethod.POST, summary = "3.21 密码验证", requestBody = @OpenApiRequestBody(content = @OpenApiContent(from = VerifyPwdReq.class)), security = {@OpenApiSecurity(name = HeaderParam.X_APP_ID), @OpenApiSecurity(name = HeaderParam.X_APP_KEY) })/*** 3.21 密码验证** @param req* @return*/public static void verifyPwd(Context ctx) {VerifyPwdReq req = ctx.bodyValidator(VerifyPwdReq.class).check(o -> StrUtil.isNotBlank(o.getLoginname()), Param.ACCOUNT_NO_NULL).check(o -> StrUtil.isNotBlank(o.getPasswd()), Param.PASSWD_NO_NULL).get();//省略代码ctx.status(HttpStatus.BAD_REQUEST_400).json(re);}}
1.访问swagger页面
2.输入X-APP-ID, X-APP-KEY的值,并点击Authorize按钮
3.进行各接口方法测试
点击各接口测试发送按钮,则会自动在header中带上X-APP-ID, X-APP-KEY的值
这篇关于javalin实现restful接口并集成swagger设置header字段的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!