面試-springboot+Mybatis實現簡單的登入功能

2020-10-26 14:00:37

思路

沒有涉及到jwt和許可權,只是簡單的使用者名稱和密碼的校驗就行嘞.
postman測試登入功能獲取資料庫中的使用者名稱資訊

pom

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.4.RELEASE</version>
    </parent>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.2.0</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.39</version>
        </dependency>
        <!--web-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--通用mapper起步依賴-->
        <dependency>
            <groupId>tk.mybatis</groupId>
            <artifactId>mapper-spring-boot-starter</artifactId>
            <version>2.0.4</version>
        </dependency>
    </dependencies>

啟動類

@SpringBootApplication
@MapperScan(basePackages ={ "com.xyy.dao"})
public class APP {
    public static void main(String[] args) {
        SpringApplication.run(APP.class, args);
    }
}

controller

get請求,請求引數放在位址列中進行傳輸

@RestController
@RequestMapping("/login")
public class LoginController {
    @Autowired
    private LoginService loginService;

    @GetMapping("/myLogin")
    public User login(@RequestParam("username") String username, @RequestParam("password") String password) {
        User user = loginService.login(username, password);
        return user;
    }
}

service邏輯層

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private LoginMapper loginMapper;

    @Override
    public User login(String username, String password) {
        User user = loginMapper.login(username, password);
        if (user == null) {
            throw new RuntimeException("使用者名稱或者密碼輸入錯誤");
        }
        return user;
    }
}

mapper通用方法

public interface LoginMapper extends Mapper<User> {
    @Select("select * from login where username=#{username} and password=#{password}")
    User login(@Param("username") String username, @Param("password") String password);
}

application.yml

server:
  port: 9008     #存取路徑 
spring:
  application:
    name: nacos-provider  #註冊中心中出現的名字
  datasource:    #地址改成自己的
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://192.168.93.128:3308/changgou-goods?   useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
    username: root
    password: root