1. 本章任务
之前的登录,没有真正的访问数据库,在上一章节我们已经实现了真实数据库的操作模块,所以本章就完整的实现下登录功能。
整体流程是:
- 用户访问登录页面login.jsp
- 输入用户名、密码后提交表单给LoginServlet
- LoginServlet调用LoginService检查登录信息是否正确
- LoginService调用UserDao访问数据库,拼装sql执行
- 登录成功后跳转后台页面index.jsp
2. 用户访问登录页面
登录页面login.jsp显示输入用户名、密码、提交按钮即可。
<form id="mainForm" method="post" action="/HomeworkSystem/LoginServlet">
请输入用户名:<input type="text" name="userName" />
<br/>
请输入密码:<input type="password" name="userPassword"/>
<br/>
<input type="submit" value="登录"/>
</form>
3. LoginServlet调用LoginService验证登录信息
LoginServlet获取表单输入信息后,调用LoginService验证登录信息
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// 处理post请求
// 设置输入输出格式、编码
response.setContentType("text/html");
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
// 获取用户在网页输入的用户名和密码
String userName = request.getParameter("userName");
String userPassword = request.getParameter("userPassword");
LoginService lc = new LoginService();
User user = null;
String tipInfo = "";// 提示内容
String page = "";// 跳转页面
try {
user = lc.checkLogin(userName, userPassword);
if (user == null) {
// 跳转到错误提示页面,并提示用户不存在
tipInfo = "用户不存在";
page = "tip.jsp";
} else {
// 登录成功,记录用户信息到Session,同时跳转管理后台页面
request.getSession().setAttribute("loginUser", user);
page = "index.jsp";
// 设置菜单
String[][] loginMenus = Constants.roleMenuMap.get(user.getUserRole());
request.getSession().setAttribute("loginMenus", loginMenus);
}
// 根据用户角色显示不同内容
} catch (Exception e) {
// 跳转到错误提示页面,并提示相应错误信息
tipInfo = e.getMessage();
page = "tip.jsp";
}
request.setAttribute("tipInfo", tipInfo);// 设置同手信息
request.getRequestDispatcher("/" + page).forward(request, response);// 跳转到page页面
}
4. LoginService调用UserDao验证用户信息
首先在UserDao内开发方法,通过用户名、密码获取用户信息。
/**
* 通过用户名、密码获取用户
*/
public List<User> getUser(String name, String password) {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
List<User> users = new ArrayList<User>();
try {
conn = DbUtils.getConnection();
String sql = "select * from user where user_name=? and user_password=?";
ps = conn.prepareStatement(sql);
ps.setString(1, name);
ps.setString(2, password);
rs = ps.executeQuery();
while (rs.next()) {
users.add(makeOneUser(rs));
}
} catch (SQLException e) {
} finally {
DbUtils.releaseConnection(rs, ps, conn);
}
return users;
}
然后在LoginService内完善验证用户信息的方法。
public class LoginService {
public User checkLogin(String userName, String userPassword) throws Exception {
if (userName.equals("") || userPassword.equals("")) {
// 抛出输入信息异常
throw new Exception("用户名和密码不能为空");
}
User user = null;
try {
UserDao userDao = new UserDao();
List<User> list = userDao.getUser(userName, userPassword);
if (list.size() == 1) {// 只有匹配出一个用户时,才是合法登录
user = list.get(0);
}
} catch (Exception e) {
// 抛出数据库异常
throw new Exception("数据库操作异常:" + e.getMessage());
}
return user;// 返回查询结果
}
}
5. 测试验证
在数据内构造几条测试数:
INSERT INTO `homework`.`user`(`user_id`, `user_role`, `user_name`, `user_password`) VALUES (1, 'master', '赵校长', '123');
INSERT INTO `homework`.`user`(`user_id`, `user_role`, `user_name`, `user_password`) VALUES (2, 'teacher', '钱老师', '123');
INSERT INTO `homework`.`user`(`user_id`, `user_role`, `user_name`, `user_password`) VALUES (3, 'student', '孙学生', '123');
然后启动项目,以孙学生+123登录即可。
需要注意的是,登录后左侧的菜单是根据用户角色决定的,此处用户角色为student
,所以根据Constants常量类配置,对应菜单为{ "页面1", "page1.jsp" }, { "页面2", "page2.jsp" }, { "不存在页面", "xxxx.jsp" }
。
public class Constants {
// 用于保存角色及对应的菜单信息
public static HashMap<String, String[][]> roleMenuMap = new HashMap<String, String[][]>();
static { // 使用static代码块对roleMenuMap进行初始化
// 注意,二位数组中的每一组表示一个菜单的信息,又通过map建立了角色名和菜单直接的对应关系
roleMenuMap.put("student", new String[][] { { "页面1", "page1.jsp" }, { "页面2", "page2.jsp" }, { "不存在页面", "xxxx.jsp" } });
}
}