SpringBoot2.0项目模块整合之Swagger2(自定UI,服务启动加载,拦截器),静态资源的访问

swagger是一款高效易用的嵌入式文档插件,同时支持在线测试接口,快速生成客户端代码。spring-boot-starter-swagger通过spring-boot方式配置的swagger实现。完美并且完整的支持swagger-spring的所有配置项,配置及其简单,容易上手。支持api分组配置,通过正则表达式方式分组。支持分环境配置,你可以很容易让你的项目api文档在开发环境,测试环境。

依赖包

		
			io.springfox
			springfox-swagger2
			2.7.0
		

 

model中常用的注解:@ApiModel 注解类名,@ApiModelProperty 注解方法或者参数名

UserModel

package com.swagger.model;

import java.io.Serializable;

import io.swagger.annotations.ApiModelProperty;

/**
 * 

* 角色 *

* * @author lixin([email protected]) * @since 2018-08-03 */ public class UserModel implements Serializable { private static final long serialVersionUID = 1L; @ApiModelProperty(value = "id", required = false, position = 1, example = "10001") private Long userId; @ApiModelProperty(value = "编号", required = false, position = 1, example = "10001") private String userCode; @ApiModelProperty(value = "名称", required = false, position = 1, example = "张三") private String userName; public UserModel() { } public UserModel(long userId, String userCode,String userName) { this.setUserId(userId); this.setUserCode(userCode); this.setUserName(userName); } public Long getUserId() { return userId; } public void setUserId(Long userId) { this.userId = userId; } public String getUserCode() { return userCode; } public void setUserCode(String userCode) { this.userCode = userCode; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } @Override public String toString() { return "UserModel [userId=" + userId + ", userCode=" + userCode + ", userName=" + userName + "]"; } }

控制器中常用的注解: @Api 注解控制器显示的标识,有tags和description可以配置控制器显示的标识;@ApiOperation 用来注解控制器方法显示的标识; @ApiParam 用来注解控制器方法参数的名字,控制器方法在文档中需要显示的默认值

UserController

package com.swagger.web.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.swagger.api.IUserService;
import com.swagger.model.UserModel;
import com.swagger.util.ApiConst;
import com.swagger.util.ResultEntity;

import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

/**
 * 

* 角色前端控制器 *

* * @author lixin([email protected]) * @since 2018-08-03 */ @Controller @RequestMapping("/user") public class UserController { private @Autowired IUserService userService; @ApiOperation(value = "添加") @RequestMapping(value = "/addUser", method = RequestMethod.POST, produces = { MediaType.APPLICATION_JSON_UTF8_VALUE }) public @ResponseBody ResultEntity addUser( @ApiParam(value = "id", required = true) @RequestParam(value = "userId", required = true) Long userId, @ApiParam(value = "角色编号", required = true) @RequestParam(value = "userCode", required = true) String userCode, @ApiParam(value = "角色名称", required = true) @RequestParam(value = "userName", required = true) String userName) { try { UserModel user = new UserModel(); user.setUserId(userId); user.setUserCode(userCode); user.setUserName(userName); userService.addUser(user); return new ResultEntity(ApiConst.CODE_SUCC, ApiConst.DESC_SUCC); } catch (Exception e) { e.getStackTrace(); } return new ResultEntity(ApiConst.CODE_FAIL, ApiConst.DESC_FAIL); } @ApiOperation(value = "查询") @RequestMapping(value = "/getUser", method = RequestMethod.POST, produces = { MediaType.APPLICATION_JSON_UTF8_VALUE }) public @ResponseBody ResultEntity> getUser() { try { List list = userService.getUser(); return new ResultEntity>(ApiConst.CODE_SUCC, ApiConst.DESC_SUCC,list); } catch (Exception e) { e.getStackTrace(); } return new ResultEntity>(ApiConst.CODE_FAIL, ApiConst.DESC_FAIL); } }

swaggerConfig配置

@Configuration
@EnableSwagger2
public class SwaggerConfig {

	@Bean
	public Docket customDocket() {
		return new Docket(DocumentationType.SWAGGER_2)
				.apiInfo(apiInfo())
				.select()
				.apis(RequestHandlerSelectors.basePackage("com.swagger.web.controller"))
				.paths(PathSelectors.any())
				.build();
	}

	private ApiInfo apiInfo() {
		 return new ApiInfoBuilder()
//	                .title("")
	                .description("测试接口Api")
	                .termsOfServiceUrl("127.0.0.1")
	                .version("1.0")
	                .build();
	}

然后我们在看看我们自己的Ui,虽然和v2版的差不多,但是里面有些不同

SpringBoot2.0项目模块整合之Swagger2(自定UI,服务启动加载,拦截器),静态资源的访问_第1张图片

这是我们Ui的静态资源

SpringBoot2.0项目模块整合之Swagger2(自定UI,服务启动加载,拦截器),静态资源的访问_第2张图片

实际应用中,我们会有在项目服务启动的时候就去加载一些数据或做一些事情这样的需求。 
为了解决这样的问题,Spring Boot 为我们提供了一个方法,通过实现接口 CommandLineRunner 来实现。

SwaggerCommandLineRunner

package com.swagger.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/** 
* @ClassName: SwaggerCommandLineRunner 
* @Description: TODO(启动加载swagger) 
* @author lixin
* @date 2018年8月17日 下午4:17:32 
*  
*/
@Component
@Order(value = 1)
public class SwaggerCommandLineRunner implements CommandLineRunner {

	private static Logger logger = LoggerFactory.getLogger(SwaggerCommandLineRunner.class);

	@Override
	public void run(String... args) throws Exception {
		logger.debug(">>>>>>>>>>>>>>服务启动加载:swagger初始化<<<<<<<<<<<<<");
	}

}


OK,下面来说一说SpringBoot 的拦截器配置,这里的拦截器配置分为  SpringBoot 1.X版本和 SpringBoot 2.X版本:

SpringBoot 1.X用的是 继承 WebMvcConfigurerAdapter类;

在SpringBoot 2.X中,WebMvcConfigurerAdapter这个类已经过时了,可以用继承WebMvcConfigurationSupport,也可以实现 WebMvcConfigurer这个接口;在使用这个SpringBoot 2.X配置拦截器后,发现静态资源居然也被拦截了,这里就需要我们在过滤条件时,放开静态资源路径,我使用的是实现 WebMvcConfigurer这个接口。下面是拦截器的配置:

WebInterceptor

package com.swagger.config;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import net.sf.json.JSONObject;

/**  
* @ClassName: WebInterceptor  
* @Description: TODO()  
* @author lixin([email protected])  
* @date 2018年8月18日 下午2:58:42  
* @version V1.0  
*/ 
public class WebInterceptor implements HandlerInterceptor {
	
	 @Override
	    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
		 System.out.println("==============  request before  ==============");
	        httpServletResponse.addHeader("Access-Control-Allow-Origin", "*");
	        httpServletResponse.addHeader("Access-Control-Allow-Methods", "*");
	        httpServletResponse.addHeader("Access-Control-Max-Age", "1800");
	        httpServletResponse.addHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, token");
	        httpServletResponse.addHeader("Access-Control-Allow-Credentials", "true");
	        httpServletResponse.setContentType("application/json;charset=UTF-8");
	        httpServletResponse.setHeader("Cache-Control", "no-cache");
	        String token = httpServletRequest.getHeader("token");
			if(null != token){
				return true;
			}
			PrintWriter out = httpServletResponse.getWriter();
			JSONObject res = new JSONObject();
		    res.put("success","false");
		    res.put("msg","登录信息失效,请重新登录!");
		    out.append(res.toString());
			out.flush();  
			return false;
	    }

	    @Override
	    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
	        System.out.println("==============  request  ==============");
	    }

	    @Override
	    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
	        System.out.println("==============  request completion  ==============");
	    }
}

WebMvcConfig

package com.swagger.config;

import java.util.Arrays;

import javax.servlet.MultipartConfigElement;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**  
* @ClassName: WebMvcConfig  
* @Description: TODO()  
* @author lixin([email protected])  
* @date 2018年8月18日 下午2:58:52  
* @version V1.0  
*/ 
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
	
	private static Logger logger = LoggerFactory.getLogger(SwaggerCommandLineRunner.class);

	/* (非 Javadoc)
	* 

Title: addCorsMappings

*

Description: 跨域

* @param registry * @see org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter#addCorsMappings(org.springframework.web.servlet.config.annotation.CorsRegistry) */ @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins("*") .allowCredentials(true) .allowedMethods("GET", "POST", "DELETE", "PUT") .maxAge(3600); } public void addInterceptors(InterceptorRegistry registry) { // registry.addInterceptor(new WebInterceptor()); registry.addInterceptor(new WebInterceptor()).excludePathPatterns(Arrays.asList("/static/**","/api/**")); //放开静态资源拦截 logger.debug(">>>>>>>>>>>>>> 拦截器注册完毕<<<<<<<<<<<<<"); } /** 上传附件容量限制 */ @Bean public MultipartConfigElement multipartConfigElement() { MultipartConfigFactory factory = new MultipartConfigFactory(); factory.setMaxFileSize("102400KB"); factory.setMaxRequestSize("112400KB"); return factory.createMultipartConfig(); } }

OK到这里,我们的配置也就结束了。

参考文档:https://docs.spring.io/spring-boot/docs/2.0.4.RELEASE/reference/htmlsingle/

Github下载路径:测试项目demo

访问的路径是:http://localhost:8001/api/index.html,下面是我做测试的图

SpringBoot2.0项目模块整合之Swagger2(自定UI,服务启动加载,拦截器),静态资源的访问_第3张图片

不填token

SpringBoot2.0项目模块整合之Swagger2(自定UI,服务启动加载,拦截器),静态资源的访问_第4张图片

填入token

SpringBoot2.0项目模块整合之Swagger2(自定UI,服务启动加载,拦截器),静态资源的访问_第5张图片

你可能感兴趣的:(springboot)