springmvc 集成 swagger2,同时项目中遗留struts2的解决办法

struts2项目中,如想增加swagger支持,必须引入springmvc,同时,springmvc对.do进行拦截

默认项目已经支持springmvc,此处不展开如何使struts2项目支持springmvc

1、引入jar包

<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-core</artifactId>
			<version>2.8.7</version>
		</dependency>
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
			<version>2.8.7</version>
		</dependency>
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-annotations</artifactId>
			<version>2.8.7</version>
		</dependency>

		<!--springfox的核心jar包 -->
		<dependency>
			<groupId>io.springfox</groupId>
			<artifactId>springfox-swagger2</artifactId>
			<version>2.9.2</version>
		</dependency>
		<!--springfox-ui的jar包(里面包含了swagger的界面静态文件) -->
		<dependency>
			<groupId>io.springfox</groupId>
			<artifactId>springfox-swagger-ui</artifactId>
			<version>2.9.2</version>
		</dependency>

       <!-- swagger增强页面,默认的太丑 -->
       <dependency>
		    <groupId>com.github.xiaoymin</groupId>
		    <artifactId>swagger-bootstrap-ui</artifactId>
		    <version>1.8.9</version>
		</dependency>

 

2、加入WebMvcConfigurerAdapter ,否则打开swaggerUI页面,会有弹框提示无法使用

package com.mhm.listener;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
@EnableWebMvc
public class WebMvcConfigurer extends WebMvcConfigurerAdapter {

	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {

		registry.addResourceHandler("swagger-ui.html").addResourceLocations(
				"classpath:/META-INF/resources/");

		registry.addResourceHandler("/webjars/**").addResourceLocations(
				"classpath:/META-INF/resources/webjars/");

        registry.addResourceHandler("/doc.html").addResourceLocations(
				"/doc.html");

	}
}

3、加入swagger2的配置类

package com.mhm.swagger;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
@EnableWebMvc
public class SwaggerConfig {
	@Bean
	public Docket docket() {
		return new Docket(DocumentationType.SWAGGER_2)
				.apiInfo(apiInfo())
				.select()
				.apis(RequestHandlerSelectors
						.basePackage("com.mhm.swagger.api"))
				.paths(PathSelectors.any()).build();
	}

	public ApiInfo apiInfo() {
		return new ApiInfoBuilder()
				.title("海蓝利科接口文档")
				.description("物联网接口文档")
				.termsOfServiceUrl("")
				.version("1.0").build();
	}
}

 

package com.mhm.swagger;

import io.swagger.models.Path;
import io.swagger.models.Swagger;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.stereotype.Component;

@Aspect
@EnableAspectJAutoProxy
@Component
public class SwaggerApiSuffixAspect {
	
	@AfterReturning(pointcut="execution(public io.swagger.models.Swagger springfox.documentation.swagger2.mappers.ServiceModelToSwagger2MapperImpl.mapDocumentation(..))",
            returning="swagger")
	public void doBeforeBussinessCheck(Swagger swagger){
        Map<String, Path> paths = swagger.getPaths();
        if(null != paths){
            Map<String, Path> newPaths = new HashMap<String, Path>(paths);
            paths.clear();
            Iterator<String> it = newPaths.keySet().iterator();
            while(it.hasNext()){
                String oldKey = it.next();
                // 添加模式后缀 .do
                String newKey = oldKey  + ".do";
                paths.put(newKey, newPaths.get(oldKey));
            }
            newPaths = null;
        }
    }
	
}

 

4、springmvc.xml配置文件中加入swagger2的支持

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"

	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
	http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
	http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.3.xsd
	http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
	http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
	"
	default-lazy-init="true">

	<context:component-scan base-package="com.mhm" />
	
	
	<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping" />
	<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
		<property name="messageConverters">
			<list>
				<bean
					class="org.springframework.http.converter.StringHttpMessageConverter">
					<property name="supportedMediaTypes">
						<list>
							<value>text/plain;charset=UTF-8</value>
							<value>text/html;charset=UTF-8</value>
							<value>applicaiton/javascript;charset=UTF-8</value>
						</list>
					</property>
				</bean>
			</list>
		</property>
	</bean>
	
	
	<!-- 注册视图解析器,根据返回值指定到某个页面 -->
	<bean id="viewResolver"
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="viewClass"
			value="org.springframework.web.servlet.view.JstlView" />
		<property name="prefix" value="/"></property><!--页面文件的路径,在根目录下 -->

	</bean>


	<mvc:resources mapping="swagger-ui.html" location="classpath:/META-INF/resources/" />
	<mvc:resources mapping="/webjars/**"
		location="classpath:/META-INF/resources/webjars/" />
	<bean id="/swaggerConfig" class="com.mhm.swagger.SwaggerConfig" />


</beans>

web.xml

注意:此处把springmvc的访问路径后缀改为*.do,而不是用的/,是为了防止springmvc的/把所有的访问都拦截了,导致struts2不能使用

<servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:spring-mvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  
  <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>*.do</url-pattern>
    
    <url-pattern>/v2/api-docs</url-pattern>
    <url-pattern>/swagger-resources</url-pattern>
    <url-pattern>/swagger-resources/configuration/security</url-pattern>
    <url-pattern>/swagger-resources/configuration/ui</url-pattern>
    
  </servlet-mapping>

 

 

 

5、API示例

package com.mhm.swagger.api;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;

import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.mhm.entity.Userinfo;


@RestController
@RequestMapping("userinfo")
@Api(value = "用户管理类")
public class UserinfoController {
	
    /**
    * 增加用户
    * @param userinfo
    * @return
    */
   @PostMapping(value = "userinfo")
   @ApiOperation(value = "新增一个用户", notes = "新增之后返回对象")
   @ApiImplicitParam(paramType = "query", name = "userinfo", value = "用户", required = true)
   @ApiResponse(code = 400, message = "参数没有填好", response = String.class)
   public String insert(Userinfo userinfo){
	   System.out.println(userinfo.toString());
	   return "INSERT OK";
   }
   
   
   /**
    * 删除单个用户
    * @param id
    * @return
    */
    @DeleteMapping(value = "userinfo/{id}")
    @ApiOperation(value = "删除用户",notes = "根据成员id删除单个用户")
    @ApiImplicitParam(paramType = "path",name = "id",value = "用户id",required = true,dataType = "Integer")
    @ApiResponse(code = 400,message = "参数没有填好",response = String.class)
    public String delete(@PathVariable("id")Integer id){
    	System.out.println(id.toString());
 	   	return "DELETE OK";
    }
   
   
}

6、本地访问:http://localhost:9207/web/swagger-ui.html   或 http://localhost:9207/web/doc.html

doc.html是增强页面,比较美观

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值