在pom.xml添加相关依赖
<!-- swagger2核心依赖 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.6.1</version>
</dependency>
<!-- swagger-ui为项目提供api展示及测试的界面 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.6.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.2.3</version>
</dependency>
其主要作用jar包为:
springfox-swagger2-2.6.1.jar
swagger-annotations-1.5.10.jar
swagger-models-1.5.10.jar
springfox-spi-2.6.1.jar
springfox-core-2.6.1.jar
springfox-schema-2.6.1.jar
springfox-swagger-common-2.6.1.jar
springfox-spring-web-2.6.1.jar
guava-17.0.jar
spring-plugin-core-1.2.0.RELEASE.jar
spring-plug-metadata-1.2.0.RELEASE.jar
spring-swagger-ui-2.6.1.jar
jackson-databind-2.2.3.jar
jackson-annotations-2.2.3.jar
通过@Configuration或在springmvc.xml中实例化配置类bean
//@Configuration
@EnableWebMvc
@EnableSwagger2
public class ApiConfig {
@Bean
public Docket userDocket(){
return new Docket(DocumentationType.SWAGGER_2)
.groupName("user") //分组
.genericModelSubstitutes(DeferredResult.class)
// .genericModelSubstitutes(ResponseEntity.class)
.useDefaultResponseMessages(false)
.forCodeGeneration(false)
.pathMapping("/")
.select()
.paths(PathSelectors.ant("/user/**")) //自己项目路径,过滤的接口.paths(or(regex("/user/.*")))
.build()
.apiInfo(userApiInfo());
}
@Bean
public Docket postDocket(){
return new Docket(DocumentationType.SWAGGER_2)
.groupName("post")
.genericModelSubstitutes(DeferredResult.class)
// .genericModelSubstitutes(ResponseEntity.class)
.useDefaultResponseMessages(false)
.forCodeGeneration(false)
.pathMapping("/")
.select()
.paths(PathSelectors.ant("/post/**"))//过滤的接口.paths(or(regex("/user/.*")))
.build()
.apiInfo(userApiInfo());
}
private ApiInfo userApiInfo() { //样式
return new ApiInfoBuilder()
.title("Electronic Health Record(EHR) Platform API")//大标题
.description("EHR Platform's REST API, all the applications could access the Object model data via JSON.")//详细描述
.version("1.0")//版本
.termsOfServiceUrl("NO terms of service")
.contact(new Contact("chai", "http://blog.csdn.net/catoop", "chaishuai@hikvision.com.cn")) //作者
.license("The Apache License, Version 2.0")
//.licenseUrl("http://www.apache.org/licenses/LICENSE-2.0.html")
.build();
}
}
<!-- 引用Swagger默认配置 或 自己定义的配置-->
<bean class="org.chai.ApiConfig" id="swagger2Config">
在决定用@Configuration
注解来加载,那么就必须保证这个类所在的路径刚好在springmvc
的component-scan
的配置的base-package
范围内
注意:配置静态资源访问,否则会被springmvc当做请求处理,而找不到相关页面,显示404
!-- 静态资源访问 -->
<mvc:default-servlet-handler/>
<mvc:resources mapping="swagger-ui.html" location="classpath:/META-INF/resources/"/>
<mvc:resources mapping="/webjars/**" location="classpath:/META-INF/resources/webjars/"/>
部署发布,http://localhost:8080/ssm-demo/swagger-ui.html, 成功
通过一些swagger注解,可以整理swagger-ui.html页面
@Api:修饰整个类,描述Controller的作用
@ApiOperation:描述一个类的一个方法,或者说一个接口
@ApiParam:单个参数描述
@ApiModel:用对象来接收参数
@ApiProperty:用对象接收参数时,描述对象的一个字段
@ApiResponse:HTTP响应其中1个描述
@ApiResponses:HTTP响应整体描述
@ApiIgnore:使用该注解忽略这个API
@ApiClass
@ApiError
@ApiErrors
@ApiParamImplicit
@ApiParamsImplicit
不清楚为啥,@Api后,单点方法不能展开了,只能通过页面Expand Operations 展开
//@Api(value="用户controller", tags="用户操作接口")
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@Autowired
private LoginLogService loginLogService;
//用户登录
@RequestMapping(value = "/userLogin", method=RequestMethod.POST)
@ApiOperation(value="获取用户信息", httpMethod="POST", notes="注意用户信息列表")
public String userLogin(@RequestBody @ApiParam(name="用户对象", value="传入json格式", required=true)User loginUser, HttpServletRequest request, RedirectAttributes redirect) {
//通过用户名查找User对象
User user = userService.getUserByUserName(loginUser.getUserName());
String password = "";
if (user != null) {
password = userService.getPassword(user.getUserName());
}
//判断登录信息是否正确
if (user != null && loginUser.getPassword().equals(password)) {
//获取登录基本信息
String lastIp = request.getRemoteAddr();
String userName = user.getUserName();
Timestamp lastLoginTime = new Timestamp(new Date().getTime());
//更新用户信息
user.setLastIp(lastIp);
user.setLastLoginTime(lastLoginTime);
user.setCredit(5 + user.getCredit());
userService.updateUserByUserName(user);
//更新用户登录日志
UserLoginLog userLoginLog = new UserLoginLog();
userLoginLog.setUserName(userName);
userLoginLog.setLoginIp(lastIp);
userLoginLog.setLoginDateTime(lastLoginTime);
loginLogService.addUserLoginLog(userLoginLog);
//登录成功,跳转到页面
request.getSession().setAttribute("username", user.getUserName());
return "redirect:/main";
}
//登录失败,跳转页面
request.setAttribute("Msg", "登录失败");
return "error";
}
//显示个人信息
@RequestMapping(value="/listUserInfo", method=RequestMethod.GET)
public String listUserInfo(@ApiParam(name="username", value="用户名", required=true)String username, HttpServletRequest request) {
User user = userService.getUserByUserName(username);
request.setAttribute("user", user);
return "user/userInfo";
}
//用户注销功能
@ApiOperation(value="用户注销", httpMethod="POST",notes="注意用户退出")
@RequestMapping(value="/loginOut")
public String loginOut(HttpServletRequest request) {
request.getSession().removeAttribute("username");
return "index";
}
}
@ApiModel(value="user对象",description="用户对象user")
public class User implements Serializable{
private int userId;
@ApiModelProperty(value="用户名",name="username",required=true,example="xiao")
private String userName;
参考借鉴: