1 创建servlet
/**
* 处理用户登录请求
*/
@WebServlet("/login.do")
public class UserLoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String username = req.getParameter("username");
String userpwd = req.getParameter("userpwd");
try {
UserLoginService userLoginService = new UserLoginServiceImpl();
Users users = userLoginService.userLogin(username, userpwd);
//建立客户端与服务端的会话状态
HttpSession session = req.getSession();
session.setAttribute(Constants.USER_SESSION_KEY, users);
//跳转首页 使用重定向 可以改变地址页url
resp.sendRedirect("main.jsp");
} catch (UserNotFoundException e) {
req.setAttribute("msg", e.getMessage());
req.getRequestDispatcher("login.jsp").forward(req, resp);
} catch (Exception e) {
resp.sendRedirect("error.jsp");
}
}
}
也就是一开始登录页面from表单提交的账号,密码进行接收。
2 主页设计
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2020/7/6 0006
Time: 12:11
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>信息管理系统界面</title>
</head>
<frameset rows="*,31" cols="*" frameborder="no" border="0" framespacing="0">
<frameset cols="187,*" frameborder="no" border="0" framespacing="0">
<frame src="left.jsp" name="leftFrame" scrolling="No" noresize="noresize" id="leftFrame" title="leftFrame" />
<frame src="index.jsp" name="rightFrame" id="rightFrame" title="rightFrame" />
</frameset>
<frame src="footer.jsp" name="bottomFrame" scrolling="No" noresize="noresize" id="bottomFrame" title="bottomFrame" />
</frameset>
<noframes><body>
</body></noframes>
</html>
3 测试结果
输入错误密码
输入正确账号密码
4 不足之处
当用户不登录其实也可以访问我们的后台,这时候需要写一个过滤器进行拦截