003.实现用户登录Model层
1.创建实体类(entity下)
package com.imooc.oa.entity; public class User { private Long userId; //user_id private String username; private String password; private Long employeeId; private Integer salt; @Override public String toString() { return "User{" + "userId=" + userId + ", username='" + username + '\'' + ", password='" + password + '\'' + ", employeeId=" + employeeId + ", salt=" + salt + '}'; } public Long getUserId() { return userId; } public void setUserId(Long userId) { this.userId = userId; } 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 Long getEmployeeId() { return employeeId; } public void setEmployeeId(Long employeeId) { this.employeeId = employeeId; } public Integer getSalt() { return salt; } public void setSalt(Integer salt) { this.salt = salt; } }
2.创建user.xml(resources/user.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="usermapper"> <select id="selectByUsername" parameterType="String" resultType="com.imooc.oa.entity.User"> select * from sys_user where username = #{value} </select> </mapper>
3.在mybatis-config.xml进行注册
<mappers> <mapper resource="mappers/user.xml"/> </mappers>
4.创建mapper(com.imooc.oa.entity.User)zaimvc业务中,mapper不包含业务逻辑,只操作数据库
package com.imooc.oa.mapper; import com.imooc.oa.entity.User; import com.imooc.oa.utils.MybatisUtils; public class UserMapper { public User selectByUsername(String username) { User user = (User) MybatisUtils.executeQuery(sqlSession -> sqlSession.selectOne("usermapper.selectByUsername", username)); return user; } }
5.在service中进行业务逻辑(package com.imooc.oa.service)
package com.imooc.oa.service; import com.imooc.oa.entity.User; import com.imooc.oa.mapper.UserMapper; import com.imooc.oa.service.exception.LoginException; public class UserService { private UserMapper userMapper = new UserMapper(); /** * 根据前台输入进行登录校验 * @param username 前台输入的用户名 * @param password 前台输入的密码 * @return 校验通过后,包含对应用户数据的User实体类 * @throws LoginException 用户登录异常 */ public User checkLogin(String username , String password){ User user = userMapper.selectByUsername(username); if(user == null){ throw new LoginException("用户名不存在"); } if(!password.equals(user.getPassword())){ throw new LoginException("密码错误"); } return user; } }
5.1在service包下创建自定义异常exception(com.imooc.oa.service.exception)
package com.imooc.oa.service.exception; public class LoginException extends RuntimeException{ public LoginException(String message){ super(message);//使用父类的方法 } }