javalin实现restful接口并集成swagger设置header字段

2024-04-20 07:08

本文主要是介绍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字段的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/919599

相关文章

SpringBoot请求参数接收控制指南分享

《SpringBoot请求参数接收控制指南分享》:本文主要介绍SpringBoot请求参数接收控制指南,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录Spring Boot 请求参数接收控制指南1. 概述2. 有注解时参数接收方式对比3. 无注解时接收参数默认位置

Go语言开发实现查询IP信息的MCP服务器

《Go语言开发实现查询IP信息的MCP服务器》随着MCP的快速普及和广泛应用,MCP服务器也层出不穷,本文将详细介绍如何在Go语言中使用go-mcp库来开发一个查询IP信息的MCP... 目录前言mcp-ip-geo 服务器目录结构说明查询 IP 信息功能实现工具实现工具管理查询单个 IP 信息工具的实现服

SpringBoot基于配置实现短信服务策略的动态切换

《SpringBoot基于配置实现短信服务策略的动态切换》这篇文章主要为大家详细介绍了SpringBoot在接入多个短信服务商(如阿里云、腾讯云、华为云)后,如何根据配置或环境切换使用不同的服务商,需... 目录目标功能示例配置(application.yml)配置类绑定短信发送策略接口示例:阿里云 & 腾

SpringBoot项目中报错The field screenShot exceeds its maximum permitted size of 1048576 bytes.的问题及解决

《SpringBoot项目中报错ThefieldscreenShotexceedsitsmaximumpermittedsizeof1048576bytes.的问题及解决》这篇文章... 目录项目场景问题描述原因分析解决方案总结项目场景javascript提示:项目相关背景:项目场景:基于Spring

Spring Boot 整合 SSE的高级实践(Server-Sent Events)

《SpringBoot整合SSE的高级实践(Server-SentEvents)》SSE(Server-SentEvents)是一种基于HTTP协议的单向通信机制,允许服务器向浏览器持续发送实... 目录1、简述2、Spring Boot 中的SSE实现2.1 添加依赖2.2 实现后端接口2.3 配置超时时

Spring Boot读取配置文件的五种方式小结

《SpringBoot读取配置文件的五种方式小结》SpringBoot提供了灵活多样的方式来读取配置文件,这篇文章为大家介绍了5种常见的读取方式,文中的示例代码简洁易懂,大家可以根据自己的需要进... 目录1. 配置文件位置与加载顺序2. 读取配置文件的方式汇总方式一:使用 @Value 注解读取配置方式二

一文详解Java异常处理你都了解哪些知识

《一文详解Java异常处理你都了解哪些知识》:本文主要介绍Java异常处理的相关资料,包括异常的分类、捕获和处理异常的语法、常见的异常类型以及自定义异常的实现,文中通过代码介绍的非常详细,需要的朋... 目录前言一、什么是异常二、异常的分类2.1 受检异常2.2 非受检异常三、异常处理的语法3.1 try-

Java中的@SneakyThrows注解用法详解

《Java中的@SneakyThrows注解用法详解》:本文主要介绍Java中的@SneakyThrows注解用法的相关资料,Lombok的@SneakyThrows注解简化了Java方法中的异常... 目录前言一、@SneakyThrows 简介1.1 什么是 Lombok?二、@SneakyThrows

Java中字符串转时间与时间转字符串的操作详解

《Java中字符串转时间与时间转字符串的操作详解》Java的java.time包提供了强大的日期和时间处理功能,通过DateTimeFormatter可以轻松地在日期时间对象和字符串之间进行转换,下面... 目录一、字符串转时间(一)使用预定义格式(二)自定义格式二、时间转字符串(一)使用预定义格式(二)自

Spring 请求之传递 JSON 数据的操作方法

《Spring请求之传递JSON数据的操作方法》JSON就是一种数据格式,有自己的格式和语法,使用文本表示一个对象或数组的信息,因此JSON本质是字符串,主要负责在不同的语言中数据传递和交换,这... 目录jsON 概念JSON 语法JSON 的语法JSON 的两种结构JSON 字符串和 Java 对象互转