美文网首页
swagger2的knife4j-spring-boot-sta

swagger2的knife4j-spring-boot-sta

作者: Leo_23 | 来源:发表于2022-10-02 08:38 被阅读0次

    knife4j-spring-boot-starter版本3.0.3使用

    github链接参考

    maven导入依赖

    <dependency>
                <groupId>com.github.xiaoymin</groupId>
                <artifactId>knife4j-spring-boot-starter</artifactId>
                <version>3.0.3</version>
            </dependency>
    

    config包下面创建Knife4jConfig.class

    package com.leo23.config;
    
    import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import springfox.documentation.builders.ApiInfoBuilder;
    import springfox.documentation.builders.PathSelectors;
    import springfox.documentation.builders.RequestHandlerSelectors;
    import springfox.documentation.service.ApiInfo;
    import springfox.documentation.service.Contact;
    import springfox.documentation.spi.DocumentationType;
    import springfox.documentation.spring.web.plugins.Docket;
    import springfox.documentation.swagger2.annotations.EnableSwagger2;
    
    @Configuration
    @EnableSwagger2
    @EnableKnife4j
    public class Knife4jConfig {
        @Bean
        public Docket createRestApi() {
            return new Docket(DocumentationType.SWAGGER_2)
                    .useDefaultResponseMessages(false)
                    .apiInfo(apiInfo())
                    .select()
                    .apis(RequestHandlerSelectors.basePackage("com.leo23.controller"))
                    .paths(PathSelectors.any())
                    .build();
        }
    
        private ApiInfo apiInfo() {
            return new ApiInfoBuilder()
                    .description("我的接口测试文档")
                    .contact(new Contact("leo", "http://www.leo**.com", "leo493852**@163.com"))
                    .version("v1.0")
                    .title("API接口测试文档")
                    .build();
        }
    }
    
    

    配置类

    package com.leo23.config;
    
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
    
    
    @Configuration
    public class WebMvcConfig extends WebMvcConfigurationSupport {
    
        @Override
        protected void addResourceHandlers(ResourceHandlerRegistry registry) {
            // Swagger Knife4j
            registry.addResourceHandler("/doc.html").addResourceLocations("classpath:/META-INF/resources/");
            registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
            
        }
    }
    

    设置静态资源映射

    package com.leo23.config;
    
    import com.leo23.common.JacksonObjectMapper;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.http.converter.HttpMessageConverter;
    import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
    import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
    
    import java.util.List;
    
    @Configuration
    public class WebMvcConfig extends WebMvcConfigurationSupport {
        @Override
        protected void addResourceHandlers(ResourceHandlerRegistry registry) {
            /**
             * 设置静态资源映射
             */
            registry.addResourceHandler("/backend/**").addResourceLocations("classpath:/backend/");
            registry.addResourceHandler("/front/**").addResourceLocations("classpath:/front/");
    
            registry.addResourceHandler("/doc.html").addResourceLocations("classpath:/META-INF/resources/");
            registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
        }
    
        /**
         * 扩展mvc框架的消息转换器
         *
         * @param converters
         */
        @Override
        protected void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
            // 创建消息转换器对象
            MappingJackson2HttpMessageConverter messageConverter = new MappingJackson2HttpMessageConverter();
            // 设置对象转换器,底层使用Jackson将Java对象转换为json
            messageConverter.setObjectMapper(new JacksonObjectMapper());
            // 将上面的消息转换器对象追加到mvc框架的转换器集合中,放在最前面(0)
            converters.add(0, messageConverter);
        }
    }
    

    过滤器添加地址过滤

    package com.leo23.filter;
    
    import com.alibaba.fastjson.JSON;
    import com.leo23.common.BaseContext;
    import com.leo23.common.R;
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.util.AntPathMatcher;
    
    import javax.servlet.*;
    import javax.servlet.annotation.WebFilter;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    
    /**
     * 检查用户是否登录
     */
    @WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
    @Slf4j
    public class LoginCheckFilter implements Filter {
        // 路径匹配器,支持通配符
        public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();
    
        @Override
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
            HttpServletRequest request = (HttpServletRequest) servletRequest;
            HttpServletResponse response = (HttpServletResponse) servletResponse;
            String requestURI = request.getRequestURI();
            // 定义不需要处理的请求的路径
            String[] urls = {
                    "/employee/login",
                    "/employee/logout",
                    "/backend/**",
                    "/front/**",
                    "/common/**",
                    "/user/sendMsg",
                    "/user/login",
    
                   "/doc.html",
                    "/webjars/**",
                    "/swagger-resources",
                    "/v2/api-docs",
            };
            boolean check = check(urls, requestURI);
            // 如果不需要处理,放行
            if (check) {
                log.info("本次请求{}, 不需要处理", request.getRequestURI());
                filterChain.doFilter(request, response);
                return;
            }
            // 4-1.后台判断登录状态,如果已登录,放行
            if (request.getSession().getAttribute("employee") != null) {
                Long empId = (Long) request.getSession().getAttribute("employee");
                BaseContext.setCurrentId(empId);
                log.info("用户已登录, id: {}", empId);
                filterChain.doFilter(request, response);
                return;
            }
    
            // 4-2.移动端判断登录状态,如果已登录,放行
            if (request.getSession().getAttribute("user") != null) {
                Long userId = (Long) request.getSession().getAttribute("user");
                BaseContext.setCurrentId(userId);
                log.info("移动端用户已登录, id: {}", userId);
                filterChain.doFilter(request, response);
                return;
            }
            // 未登录
            log.info("用户未登录");
            response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        }
    
        /**
         * 路径匹配,检查本次请求是否需要放行
         *
         * @param urls
         * @param requestURI
         * @return
         */
        public boolean check(String[] urls, String requestURI) {
            for (String url : urls) {
                boolean match = PATH_MATCHER.match(url, requestURI);
                if (match) {
                    return true;
                }
            }
            return false;
        }
    }
    
    

    相关文章

      网友评论

          本文标题:swagger2的knife4j-spring-boot-sta

          本文链接:https://www.haomeiwen.com/subject/ltyjartx.html