11.27
模块 3:登录功能(核心入口,区分角色)
- DAO 层(UserDao.java):查询用户信息
创建com.student.daily.dao.UserDao.java,实现根据userId和userCategory查询用户(登录验证逻辑):
java
运行
package com.student.daily.dao;
import com.student.daily.entity.User;
import com.student.daily.util.DBUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
-
用户DAO层(操作t_user表)
-
班级:2023级XX班
-
作者:XXX
-
学号:2023XXXX
-
日期:2024-12-27
*/
public class UserDao {
// 登录验证:根据userId(账号)和userCategory(角色)查询用户(注:实际项目需加密码字段,此处按题目需求简化)
public User login(String userId, Integer userCategory) {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
User user = null;
// SQL:查询指定ID和角色的用户
String sql = "SELECT user_id, user_name, user_category, group_no FROM t_user WHERE user_id = ? AND user_category = ?";try { conn = DBUtil.getConnection(); pstmt = conn.prepareStatement(sql); pstmt.setString(1, userId); pstmt.setInt(2, userCategory); rs = pstmt.executeQuery(); if (rs.next()) { // 封装查询结果为User对象 user = new User(); user.setUserId(rs.getString("user_id")); user.setUserName(rs.getString("user_name")); user.setUserCategory(rs.getInt("user_category")); user.setGroupNo(rs.getInt("group_no")); } } catch (SQLException e) { e.printStackTrace(); } finally { DBUtil.close(rs, pstmt, conn); } return user; // 若查询不到,返回null(登录失败)}
}
- Service 层(UserService.java):封装登录业务逻辑
创建com.student.daily.service.UserService.java和实现类UserServiceImpl.java:
java
运行
// UserService.java(接口)
package com.student.daily.service;
import com.student.daily.entity.User;
public interface UserService {
// 登录方法:参数为账号(userId)、角色(userCategory),返回用户信息
User login(String userId, Integer userCategory);
}
// UserServiceImpl.java(实现类)
package com.student.daily.service.impl;
import com.student.daily.dao.UserDao;
import com.student.daily.entity.User;
import com.student.daily.service.UserService;
// 业务层依赖DAO层,通过new创建DAO实例(实际项目可用Spring注入)
public class UserServiceImpl implements UserService {
private UserDao userDao = new UserDao();
@Override
public User login(String userId, Integer userCategory) {
// 简单业务校验:账号不为空
if (userId == null || userId.trim().isEmpty()) {
return null;
}
// 调用DAO层方法查询用户
return userDao.login(userId, userCategory);
}
}

浙公网安备 33010602011771号