功能上实现了登录和查询全部
Lombok spring boot SQL等
<dependencies>
<dependency>
<!--引入mp依赖 用于数据库的连接-->
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.2</version>
</dependency>
<!--引入swagger依赖 用于生成接口文档-->
<dependency>
<groupId>com.spring4all</groupId>
<artifactId>swagger-spring-boot-starter</artifactId>
<version>1.9.1.RELEASE</version>
</dependency>
<!--接口文档自动化 更加易读-->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>swagger-bootstrap-ui</artifactId>
<version>1.9.6</version>
</dependency>
<!-- Fastjson 是一个 Java 库,可以将 Java 对象转换为 JSON 格式,当然它也可以将 JSON 字符串转换为 Java 对象。-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.75</version>
</dependency>
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.8.3</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
MyConfig 注册拦截器
public class MyConfig extends WebMvcConfigurationSupport {
@Override
protected void addInterceptors(InterceptorRegistry registry){
registry.addInterceptor(new LoginInterceptor()).excludePathPatterns("/login").addPathPatterns("/**");
}
}
SwaggerConfig
* 该套 API 说明,包含作者、简介、版本、host、服务URL
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket docket(){
Docket docket = new Docket(DocumentationType.SWAGGER_2)
.apiInfo(getInfo())
.select().apis(RequestHandlerSelectors.basePackage("com.lyf.springboot.controller"))
.build();
return docket;
}
public ApiInfo getInfo(){
Contact DEFAULT_CONTACT = new Contact("", "http://www.jd.com", "[email protected]");
ApiInfo info = new ApiInfo("复习swagger", "复习swagger", "1.0", "http://www.baidu.com",
DEFAULT_CONTACT, "Apache 2.0", "http://www.apache.org/licenses/LICENSE-2.0", new ArrayList<VendorExtension>());
return info;
}
}
LoginController
@CrossOrigin是用来处理跨域请求的注解 跨域,指的是浏览器不能执行其他网站的脚本。它是由浏览器的同源策略造成的,是浏览器对JavaScript施加的安全限制。
生成的api文档会根据tags分类,直白的说就是这个controller中的所有接口生成的接口文档都会在tags这个list下;tags如果有多个值,会生成多个list,每个list都显示所有接口
@ApiOperation
使用于在方法上,表示一个http请求的操作
源码中属性太多,记几个比较常用
value用于方法描述
notes用于提示内容
tags可以重新分组(视情况而用)
@ApiParam
使用在方法上或者参数上,字段说明;表示对参数的添加元数据(说明或是否必填等)
name–参数名
value–参数说明
required–是否必填
@ApiModel()
使用在类上,表示对类进行说明,用于参数用实体类接收
value–表示对象名
description–描述
@RestController
@Api(tags = "登录API接口")
@CrossOrigin
public class LoginController {
@Autowired
private UserService userService;
@PostMapping("/login")
@ApiOperation(value = "登录接口")
@ApiImplicitParams({
@ApiImplicitParam(name = "username",value="账号",required = true),
@ApiImplicitParam(name = "password",value="密码",required = true)
})
public CommonResult Login(String username, String password){
return userService.findUserByNameAndPassword(username, password);
}
}
UserController
@RestController
@RequestMapping("/user")
@Api(tags = "用户操作API接口")
@CrossOrigin
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/list")
@ApiOperation(value ="查询所有用户")
public CommonResult list(){
return userService.findAll();
}
}
mybtais-plus
public interface UserDao extends BaseMapper<User> {
}
@Data
@TableName(value = "tbl_user")
public class User {
@TableId(type = IdType.AUTO)
private Integer userid;
private String username;
private String password;
private String realname;
private int roleid;
}
public class LoginInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response,Object handler) throws Exception{
String method = request.getMethod();
if (method.equals("OPTIONs")){
return true;
}
String token = request.getHeader("token");
if(token !=null&& JwtUtils.verifyToken(token)){
return true;
}
CommonResult commonResult = new CommonResult(5000,"请先登录",null);
response.setContentType("application/json;charset=utf-8");
response.getWriter().print(JSON.toJSONString(commonResult));
return false;
}
}
public interface UserService {
public CommonResult findUserByNameAndPassword(String username, String password);
public CommonResult findAll();
}
实现类
@Service("userService")
public class UserServiceImpl implements UserService{
@Autowired
private UserDao userDao;
@Override
public CommonResult findUserByNameAndPassword(String username, String password){
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.eq("username",username);
wrapper.eq("password",password);
User user =userDao.selectOne(wrapper);
if (user==null){
return new CommonResult(5000,"账号或密码错误",null);
}else{
String token = JwtUtils.createToken(user.getUserid()+"",user.getUsername(),user.getRealname());
return new CommonResult(2000,"登录成功",token);
}
}
@Override
public CommonResult findAll(){
List<User> users = userDao.selectList(null);
return new CommonResult(2000,"查询成功",users);
}
}
lombok
@Data
@NoArgsConstructor
@AllArgsConstructor
@ApiModel(value = "返回的公共实体类")
public class CommonResult {
@ApiModelProperty("状态码")
private Integer code;
@ApiModelProperty("信息")
private String mag;
@ApiModelProperty("数据结果")
private Object data;
}
JwtUtils
主函数当中使用此类的getInstance()函数,即可得到系统当前已经实例化的该类对象,若当前系统还没有实例化过这个类的对象,则调用此类的构造函数
public class JwtUtils {
public static String createToken(String userId, String realName, String userName){
Calendar nowTime = Calendar.getInstance();
nowTime.add(Calendar.MINUTE,30);
Date expiresDate = nowTime.getTime();
return JWT.create().withAudience(userId).
withIssuedAt(new Date())
.withExpiresAt(expiresDate)
.withClaim("username",userName)
.withClaim("realname",realName)
.sign(Algorithm.HMAC256("Hellolyf"));
}
public static boolean verifyToken(String token){
try {
DecodedJWT jwt = null;
JWTVerifier verifier = JWT.require(Algorithm.HMAC256("Hellolyf")).build();
jwt= verifier.verify(token);
return true;
} catch (Exception e) {
return false;
}
}
public static String getAudience(String token){
String audience = null;
try {
audience = JWT.decode(token).getAudience().get(0);
} catch (JWTDecodeException e) {
throw new RuntimeException("签名无效");
}
return audience;
}
public static Claim getClaimByName(String token,String name){
return JWT.decode(token).getClaim(name);
}
}
@SpringBootApplication
@MapperScan(basePackages = "com.lyf.day211springboot.dao")
public class Day211springbootApplication {
public static void main(String[] args) {
SpringApplication.run(Day211springbootApplication.class, args);
}
}
server.port=8088
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.password=root
spring.datasource.username=root
spring.datasource.url=jdbc:mysql://localhost:3306/sys?serverTimezone=Asia/Shanghai
logging.level.com.ykq.demo003.dao=debug
这是 Spring Boot 最最最核心的注解,用在 Spring Boot 主类上,标识这是一个 Spring Boot 应用,用来开启 Spring Boot 的各项能力。
其实这个注解就是 @SpringBootConfiguration、@EnableAutoConfiguration、@ComponentScan 这三个注解的组合,也可以用这三个注解来代替 @SpringBootApplication 注解。