Spring MVC API 적용 Servlet의 “/“가 아닌 ”/api/*” 형태로 매핑되면 Swagger 적용이 복잡해진다. 최근 버전은 매우 간결해짐.
// /css/*, /js/* 등에 대한 핸들러 추가.
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("css/**", "js/**", "lib/**", "images/**", "swagger-ui.js")
.addResourceLocations(WEB_JAR_RESOURCE_LOCATION,
WEB_JAR_RESOURCE_LOCATION + "css/",
WEB_JAR_RESOURCE_LOCATION + "js/",
WEB_JAR_RESOURCE_LOCATION + "lib/",
WEB_JAR_RESOURCE_LOCATION + "images/")
.setCachePeriod(0);
super.addResourceHandlers(registry);
}
@ApiIgnore
@Controller
public class SwaggerController {
@Autowired
private ResourceLoader resourceLoader;
@RequestMapping("/swagger")
public void swagger(HttpServletResponse response) throws IOException {
final Resource swaggerHtmlResource =
resourceLoader.getResource("classpath:/META-INF/resources/sdoc.jsp");
final String swaggerHtmlContents =
CoupangIOUtils.toString(swaggerHtmlResource.getInputStream(), "UTF-8");
final String refinedHtml = swaggerHtmlContents
.replaceAll("http://swagger.wordnik.com", "/api/swagger");
response.setContentType("text/html; charset=UTF-8");
final PrintWriter writer = response.getWriter();
writer.write(refinedHtml);
writer.close();
}
}