一、整合Swagger2文档API
1、pom.xml引入依赖
<!-- swagger2配置--> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.4.0</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.4.0</version> </dependency> <dependency> <groupId>com.github.xiaoymin</groupId> <artifactId>swagger-bootstrap-ui</artifactId> <version>1.6</version> </dependency>
2、添加扫描配置类 Swagger2 .java
package com.imooc.config; 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 public class Swagger2 { //http://localhost:8088/swagger-ui.html @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("com.imooc.controller")) .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("电商平台API") .contact(new Contact("imooc","http://www.imooc.com","aaa@imooc.com")) .description("API 文档") .version("1.0.1") .termsOfServiceUrl("http://www.imooc.com") .build(); } }
3、Controller层 Swagger Api 使用
package com.imooc.controller; import com.imooc.pojo.Users; import com.imooc.pojo.bo.UserBO; import com.imooc.service.UserService; import com.imooc.utils.CookieUtils; import com.imooc.utils.IMOOCJSONResult; import com.imooc.utils.JsonUtils; import com.imooc.utils.MD5Utils; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @Api(value = "注册登录",tags = "用于注册和登录的相关接口") @RestController @RequestMapping("passport") public class PassportController { @Autowired private UserService userService; @ApiOperation(value="用户名是否存在",notes = "用户名是否存在",httpMethod = "GET") @GetMapping("/usernameIsExist") public IMOOCJSONResult usernameIsExist(@RequestParam String username){ //1. if(StringUtils.isBlank(username)) { return IMOOCJSONResult.errorMsg("用户名不能为空"); } //2. boolean isExist=userService.queryUsernameIsExist(username); if (isExist) { return IMOOCJSONResult.errorMsg("用户名已经存在"); } //3.请求成功 return IMOOCJSONResult.ok(); } @ApiOperation(value="用户注册",notes = "用户注册",httpMethod = "POST") @PostMapping("/regist") public IMOOCJSONResult regist(@RequestBody UserBO userBO){ String username = userBO.getUsername(); String password = userBO.getPassword(); String confirmPwd=userBO.getConfirmPassword(); //0 if(StringUtils.isBlank(username) || StringUtils.isBlank(password)|| StringUtils.isBlank(confirmPwd)){ return IMOOCJSONResult.errorMsg("用户名或密码不能为空"); } //1 boolean isExist=userService.queryUsernameIsExist(username); if (isExist) { return IMOOCJSONResult.errorMsg("用户名已经存在"); } //2 if(password.length()<6) { return IMOOCJSONResult.errorMsg("用户密码不能少于6位"); } //3 //2 if(!password.equals(confirmPwd)) { return IMOOCJSONResult.errorMsg("两次密码不一致"); } //4 userService.creatUser(userBO); return IMOOCJSONResult.ok(); } @ApiOperation(value="用户登录",notes = "用户登录",httpMethod = "POST") @PostMapping("/login") public IMOOCJSONResult login(@RequestBody UserBO userBO, HttpServletRequest request, HttpServletResponse response) throws Exception{ String username = userBO.getUsername(); String password = userBO.getPassword(); //String confirmPwd=userBO.getConfirmPassword(); //0 if(StringUtils.isBlank(username) || StringUtils.isBlank(password) ){ return IMOOCJSONResult.errorMsg("用户名或密码不能为空"); } Users user= userService.queryUserForLogin(username, MD5Utils.getMD5Str(password)); if(user==null) { return IMOOCJSONResult.errorMsg("用户名和密码不正确"); } user=setNullProperty(user); CookieUtils.setCookie(request, response,"user", JsonUtils.objectToJson(user),true); return IMOOCJSONResult.ok(user); } @ApiOperation(value="用户退出登录",notes = "用户退出登录",httpMethod = "POST") @PostMapping("/logout") public IMOOCJSONResult logout(@RequestParam String userId,HttpServletRequest request, HttpServletResponse response){ //1 CookieUtils.deleteCookie(request, response, "user"); //TODO 用户退出登录,需要清空购物车 //TODO 分布式会话中需要清除用户数据 //2 return IMOOCJSONResult.ok(); } private Users setNullProperty(Users user) { user.setPassword(null); user.setNickname(null); user.setCreatedTime(null); return user; } }
4、访问地址:http://localhost:8088/doc.html
http://localhost:8088/swagger-ui.html
优化后地址
http://localhost:8088/doc.html
二、整合log4j打印日志
1、pom.xml引入依赖
(1)移除默认日志
<exclusions> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-logging</artifactId> </exclusion> </exclusions>
(2)添加日志框架依赖
<!-- 引入日志依赖 抽象层 与 实现层--> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.30</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.21</version> </dependency> </dependencies>
2、创建 log4j.properties 并且放到资源文件目录 src/main/resource
log4j.rootLogger=DEBUG,stdout,file log4j.additivity.org.apache=true log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.threshold=INFO log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%-5p %c{1}:%L - %m%n log4j.appender.file=org.apache.log4j.DailyRollingFileAppender log4j.appender.file.layout=org.apache.log4j.PatternLayout log4j.appender.file.DatePattern=‘.‘yyyy-MM-dd-HH-mm log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n log4j.appender.file.Threshold=INFO log4j.appender.file.append=true log4j.appender.file.File=/workspaces/logs/foodie-api/imooc.log
3、使用
package com.imooc.controller; import io.swagger.annotations.Api; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import springfox.documentation.annotations.ApiIgnore; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; @ApiIgnore @RestController public class HelloController { final static Logger logger= LoggerFactory.getLogger(HelloController.class); @GetMapping("/hello") public Object hello(){ logger.info("info:hello~"); logger.debug("debug:hello~"); logger.warn("warn:hello~"); logger.error("error:hello~"); return "Hello World"; } }