1.项目配置等,请看我上篇博客
https://blog.csdn.net/biancheng4/article/details/121653523
2.建立用户实体类
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
@ApiModel("用户实体类")
public class User {
@ApiModelProperty("用户名")
public String username;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public User(String username, String password) {
this.username = username;
this.password = password;
}
@ApiModelProperty("密码")
public String password;
}
3.建立Mapper接口
import com.school.gaoxin.entity.User;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface UserMapper {
/*
查找用户
*/
User GetUser(User user);
}
4.建立Mapper.xml文件
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.school.gaoxin.Mapper.UserMapper">
<!-- 查找信息-->
<select id="GetUser" resultType="com.school.gaoxin.entity.User">
SELECT * FROM user where userName = #{username} and password = #{password}
</select>
</mapper>
5.建立Service层
import com.school.gaoxin.Mapper.UserMapper;
import com.school.gaoxin.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserService {
@Autowired
UserMapper userMapper;
public User GetUser(User user){
return userMapper.GetUser(user);
}
}
6.建立Controller控制类
import com.school.gaoxin.Service.UserService;
import com.school.gaoxin.entity.User;
import com.school.gaoxin.utils.CommonResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
//接口
@Api(tags = "用户信息类")
@RequestMapping("/userinfo")
@RestController
@CrossOrigin //解决跨域问题
public class UserController {
@Autowired
UserService userService;
@ApiOperation("用户登录")
@PostMapping(value = "/login")
public CommonResponse Login(User user){
if (user.username.isEmpty() || user.password.isEmpty()){
return CommonResponse.error().data("errMessage" , "用户名或密码不能为空");
} else if(userService.GetUser(user) == null){
return CommonResponse.error().data("errormessage", "用户名或密码错误");
} else {
return CommonResponse.ok().data("userinfo", userService.GetUser(user));
}
}
}
7.数据库用户类
使用了一个很久之前的用户表
8.使用swagger调试接口
用户名或密码错误
正确请求