Springboot复习

功能上实现了登录和查询全部

1.所需依赖

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>

2. 基本构成

Springboot复习_第1张图片

2.1 配置文件

MyConfig 注册拦截器

  • 继承 WebMvcConfigurationSupport ,重写 addInterceptors 方法
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;
    }
}

2.2控制层

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();
    }
}

3.1 Dao层

mybtais-plus

  • Mapper接口:基本的增、删、改、查方法
  • MySqlMapper:针对MySQL的额外补充接口,支持批量插入
  • IdsMapper:使mapper支持批量ID操作
public interface UserDao extends BaseMapper<User> {
}

4.1 实体类

  • @TableName 注解用来将指定的数据库表和 JavaBean 进行映射。
@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;
}

5.1 拦截器

  • 预处理回调方法,实现处理器的预处理(如检查登陆),第三个参数为响应的处理器,自定义Controller
    • 返回值:true表示继续流程(如调用下一个拦截器或处理器);false表示流程中断(如登录检查失败),不会继续调用其他的拦截器或处理器,此时我们需要通过response来产生响应;
      */
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;
    }
}

6.1 业务层

public interface UserService {
    public CommonResult findUserByNameAndPassword(String username, String password);

    public CommonResult findAll();
}

实现类

  • QueryWrapper:条件构造抽象类,最顶端父类
@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);
    }
}

7.1 工具类

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

springboot注解1、@SpringBootApplication

这是 Spring Boot 最最最核心的注解,用在 Spring Boot 主类上,标识这是一个 Spring Boot 应用,用来开启 Spring Boot 的各项能力。

其实这个注解就是 @SpringBootConfiguration、@EnableAutoConfiguration、@ComponentScan 这三个注解的组合,也可以用这三个注解来代替 @SpringBootApplication 注解。

你可能感兴趣的:(spring,boot,java,bootstrap)