Create a SpringBoot project

Add dependencies (POM.xml)

<! MyBatis -plus-generator --> <dependency> <groupId>com.baomidou</groupId> <artifactId> MyBatis -plus-generator</artifactId> The < version > 3.4.0 < / version > < / dependency > <! --mysql--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <! --mybatis-plus--> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> The < version > 3.0.5 < / version > < / dependency > <! -- Velocity templating engine, <dependency> <groupId>org.apache.velocity</groupId> The < artifactId > velocity - engine - core < / artifactId > < version > 2.0 < / version > < / dependency > <! Lombok uses to simplify entity classes: Lombok needs to be installed --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> <! --swagger--> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> < version > 2.7.0 < / version > < / dependency > < the dependency > < groupId >. IO springfox < / groupId > < artifactId > springfox swagger - UI < / artifactId > < version > 2.7.0 < / version > < / dependency > <! -- JWT--> <dependency> <groupId> IO. Jsonwebtoken </groupId> <artifactId> JJWT </artifactId> <version>0.7.0</version> </dependency>Copy the code

Application. Properties

Driver-class-name = com.mysql.cj.jdbc.driver spring.datasource.url=jdbc:mysql://localhost:3308/tokenlogin? ServerTimezone = GMT % 2 b8 spring. The datasource. The username = root spring. The datasource. The password = # root configuration mapper XML file path mybatis-plus.mapper-locations=classpath:com/sise/wangzhan/mapper/xml/*.xmlCopy the code

4. Create table for database

Create statements

-- auto-generated definition create table member (id bigint not null comment 'iD' primary key, Openid varchar(128) charset UTf8mb4 NULL comment '微信openid', Mobile varchar(11) charset utf8MB4 default 'null COMMENT ', Password varchar(255) charset UTf8MB4 NULL comment 'password ', nickname varchar(50) charset UTf8MB4 null comment' nickname ', Sex tinyint(2) unsigned null comment 'sex 1 female, 2 male ', age tinyint unsigned NULL comment 'age ', avatar vARCHar (255) charset UTf8MB4 NULL comment' avatar ', Sign varchar(100) charset UTf8MB4 NULL comment ' ', Is_disabled tinyInt (1) default 0 not NULL comment '1 (true) 0 (false) not disabled ', is_deleted tinyInt (1) default 0 not null comment 'Logical deletion 1 (true) deleted 0 (false) not deleted ', gmt_create datetime not null comment 'create time ', gmt_modified datetime not null comment' update time ');Copy the code

5. Use MyBatis- Plus to generate code automatically

The generated code

package com.sise.wangzhan; import com.baomidou.mybatisplus.annotation.DbType; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.generator.AutoGenerator; import com.baomidou.mybatisplus.generator.config.DataSourceConfig; import com.baomidou.mybatisplus.generator.config.GlobalConfig; import com.baomidou.mybatisplus.generator.config.PackageConfig; import com.baomidou.mybatisplus.generator.config.StrategyConfig; import com.baomidou.mybatisplus.generator.config.rules.DateType; import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy; import org.junit.Test; /** * Copyright: Copyright (c) 2021 Asiainfo * * @ClassName: ucenter.CodeGenerator * @Description: * <p> * @version: v1.0.0 * @author: wangzhan * @Date: 2021/1/511:42 * <p> * Modification History: * the Date the Author Version Description * -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- * 2021/1/5 acer v1.0.0 */ public class CodeGenerator {@test public void codeGeneratorTest(){// 1 AutoGenerator(); // 2, GlobalConfig gc = new GlobalConfig(); String projectPath = System.getProperty("user.dir"); gc.setOutputDir("\\token_login_demo" + "/src/main/java"); gc.setAuthor("wangzhan"); gc.setOpen(false); // Whether to open resource manager gc.setFileOverride(false); // Whether the file overwrites gc.setServicename ("%sService"); // Remove the first letter of the Service interface I gc.setidType (idtype.auto); // Primary key policy gc.setdateType (datetype.only_date); // Define date type gC.setSwagger2 (true) in the generated entity class; // Enable Swagger2 mode MPG. SetGlobalConfig (gc); // 3, DataSourceConfig DSC = new DataSourceConfig(); dsc.setUrl("jdbc:mysql://localhost:3308/wang? serverTimezone=GMT%2B8"); dsc.setDriverName("com.mysql.cj.jdbc.Driver"); dsc.setUsername("root"); dsc.setPassword("root"); dsc.setDbType(DbType.MYSQL); mpg.setDataSource(dsc); PackageConfig PC = new PackageConfig(); / / package com sise. Wangzhan. The generator PC. SetParent (" com. Sise "); pc.setModuleName("wangzhan"); / / module name / / package com sise. Wangzhan. The controller PC. SetController (" controller "); pc.setEntity("entity"); pc.setService("service"); pc.setMapper("mapper"); mpg.setPackageInfo(pc); // 5, StrategyConfig strategy = new StrategyConfig(); / / table name strategy. SetInclude (" member "); strategy.setNaming(NamingStrategy.underline_to_camel); Strategy.settableprefix (pc.getModulename () + "_"); Strategy. setColumnNaming(namingStrategy. underline_to_camel); / / database table field mapping to the entity named strategy. The strategy setEntityLombokModel (true); / / @ Accessors, lombok model (chain = true) setter chain operation strategy. SetRestControllerStyle (true); / / restful API style controller strategy. SetControllerMappingHyphenStyle (true); // hump to hyphenate MPG. SetStrategy (strategy); // 6. Execute mpg.execute(); }}Copy the code

Note (need to change your own configuration)

1. Modification of project path

2. Data source configuration

3. Package configuration

4. Fill in the table name in the database

Pre-execution effect

Post-execution effect

Six, Mybatis- Plus automatic filling time

1. Annotation fill field

2. Realize the meta-object processor interface

The following code

package com.sise.wangzhan.servicebase.handler; import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler; import org.apache.ibatis.reflection.MetaObject; import org.springframework.stereotype.Component; import java.util.Date; @Component public class MyMetaObjectHandler implements MetaObjectHandler { @Override public void insertFill(MetaObject MetaObject) {this.setFieldValbyName ("createTime", new Date(), metaObject); this.setFieldValByName("modifiedTime", new Date(), metaObject); } @Override public void updateFill(MetaObject metaObject) { this.setFieldValByName("modifiedTime", new Date(), metaObject); }}Copy the code

Seven, need to use swagger for matching test

Writing configuration classes

package com.sise.wangzhan.config; import com.google.common.base.Predicates; 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.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; /** * @className SwaggerConfig * @description TODO 1 access address http://localhost: port number /swagger-ui.html * @date 2020/5/30 11:20 * @created by wangzhan */ @configuration // config class @enablesWagger2 // Swagger annotation Public class SwaggerConfig {// Swagger plugin @Bean public Docket webApiConfig(){ return new Docket(DocumentationType.SWAGGER_2) .groupName("webApi") .apiInfo(webApiInfo()) .select() //.paths(Predicates.not(PathSelectors.regex("/admin/.*"))) .paths(Predicates.not(PathSelectors.regex("/error.*"))) .build(); } private ApiInfo webApiInfo(){return new ApiInfoBuilder().title(" ApiInfoBuilder ").description(" this API has no description ") Version (" 1.0 "). Contact (new contact (" Java ", "http://atguigu.com", "1123 @qq.com")). The build (); }}Copy the code

Add JWT utility class

The following code

package com.sise.wangzhan.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @author wangzhan
 * @since 2019/10/16
 */
public class JwtUtils {

    //常量
    public static final long EXPIRE = 1000 * 60 * 60 * 24; //token过期时间, 这里设置的是一天的有效时间
    public static final String APP_SECRET = "ukc8BDbRigUDaY6pZFfWus2jZWLPHO"; //秘钥,自己随便设

    //生成token字符串的方法
    public static String getJwtToken(BigInteger id, String nickname){

        String JwtToken = Jwts.builder()
                // JWT的头信息
                .setHeaderParam("typ", "JWT")
                .setHeaderParam("alg", "HS256")

                // 设置过期时间
                .setSubject("onlineCourse-user")
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE))

                // 数据库中的字段
                .claim("id", id)  //设置token主体部分 ,存储用户信息
                .claim("nickname", nickname)

                // 签名哈希
                .signWith(SignatureAlgorithm.HS256, APP_SECRET)
                .compact();

        return JwtToken;
    }

    /**
     * 判断token是否存在与有效
     * @param jwtToken
     * @return
     */
    public static boolean checkToken(String jwtToken) {
        if(StringUtils.isEmpty(jwtToken)) return false;
        try {
            Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(jwtToken);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 判断token是否存在与有效
     * @param request
     * @return
     */
    public static boolean checkToken(HttpServletRequest request) {
        try {
            String jwtToken = request.getHeader("token");
            if(StringUtils.isEmpty(jwtToken)) return false;
            Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(jwtToken);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 根据token字符串获取会员id
     * @param request
     * @return
     */
    public static String getMemberIdByJwtToken(HttpServletRequest request) {
        String jwtToken = request.getHeader("token");
        if(StringUtils.isEmpty(jwtToken)) return "";
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(jwtToken);
        Claims claims = claimsJws.getBody();
        return (String)claims.get("id");
    }
}

Copy the code

You have to pay attention here

Write code

The controller layer

package com.sise.wangzhan.controller; import com.sise.wangzhan.entity.Member; import com.sise.wangzhan.service.MemberService; import com.sise.wangzhan.utils.JwtUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** ** <p> ** @author wangzhan * @since 2021-01-11 */ @restController@requestMapping ("/ /wangzhan/member")  public class MemberController { @Autowired private MemberService memberService; @ PostMapping (value = "addMember") public String addMember (@ RequestBody Member Member) {/ / sentenced to empty the if (Member = = null | | StringUtils.isEmpty(member.getNickname()) || StringUtils.isEmpty(member.getPassword()) || Stringutils.isempty (member.getMobile())){return "empty "; } int count = memberService.saveMember(member); If (count == 1){return "add success "; }else {return "Add failed "; }} @ PostMapping (value = "/ login") public String login (@ RequestBody Member Member) {/ / sentenced to empty the if (Member = = null | | StringUtils. IsEmpty (member. GetNickname () | | StringUtils. IsEmpty (member. GetPassword ())) {return "to get the user name or password is empty". } / / according to the user name, password query data Member loginMember = memberService. GetMemberByNicknameAndPassword (Member); System.out.println(" ::::::" + loginMember); system.out. println(" ::::::" + loginMember); If (loginMember == null){return "username or password error "; }else if (loginMember ! = null){ System.out.println("=========" + String.valueOf(member.getId())); JwtToken = jwTutils.getJWtToken (string.valueof (member.getid ()), member.getnickName ()); return jwtToken; } return null; }}Copy the code

2, the service layer

package com.sise.wangzhan.service; import com.sise.wangzhan.entity.Member; import com.baomidou.mybatisplus.extension.service.IService; /** * <p> ** @author wangzhan * @since 2021-01-11 */ Public Interface MemberService extends IService<Member> { Member getMemberByNicknameAndPassword(Member member); int saveMember(Member member); }Copy the code

package com.sise.wangzhan.service.impl; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.sise.wangzhan.entity.Member; import com.sise.wangzhan.mapper.MemberMapper; import com.sise.wangzhan.service.MemberService; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import org.springframework.stereotype.Service; /** * <p> ** @author wangzhan * @since 2021-01-11 */ @service public class MemberServiceImpl extends ServiceImpl<MemberMapper, Member> implements MemberService { @Override public Member getMemberByNicknameAndPassword(Member member) { QueryWrapper wrapper = new QueryWrapper(); wrapper.eq("nickname", member.getNickname()); Wrapper. Eq ("password", member.getPassword()); return baseMapper.selectOne(wrapper); } @Override public int saveMember(Member member) { int count = baseMapper.insert(member); return count; }}Copy the code

10. Swagger Test Results

User name null

Returns the token that succeeded

Obtain user information based on the token returned by the front-end

The corresponding ID type needs to be changed

And then I’m just going to look it up based on id