LoginServlet 类
package net.cf.shop.servlet;
/**
* 功能:登录处理类
* 作者:曹峰
* 日期:2019年12月5日
*/
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import net.cf.shop.bean.User;
import net.cf.shop.service.UserService;
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 设置请求对象的字符编码
request.setCharacterEncoding("utf-8");
// 获取会话对象
HttpSession session = request.getSession();
// 获取用户名
String username = request.getParameter("username");
// 获取密码
String password = request.getParameter("password");
// 定义用户服务对象
UserService userService = new UserService();
// 执行登录方法,返回用户实体
User user = userService.login(username, password);
// 判断用户登录是否成功
if (user != null) {
// 设置session属性
session.setMaxInactiveInterval(5 * 60);
session.setAttribute("username", username);
session.removeAttribute("loginMsg");
// 根据用户权限跳转到不同页面
if (user.getPopedom() == 0) {
System.out.println("用户登陆成功,进入后台管理!");
response.sendRedirect(request.getContextPath() + "/backend/management.jsp");
} else if (user.getPopedom() == 1) {
System.out.println("用户登陆成功,进入前台,显示商品类别");
response.sendRedirect(request.getContextPath() + "/showCategory");
}
} else {
System.out.println("用户名或密码错误,用户登录失败!");
// 设置session属性loginMsg
session.setAttribute("loginMsg", "用户名或密码错误!");
response.sendRedirect(request.getContextPath() + "/login.jsp");
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
开始测试
启动Tomcat服务器
没用登陆成功,查看下我的数据库是否是密码错误
哦!!! 原来是username,而我写成了name,再来试试
成功进入了后台,为什么没报404错误呢?
因为我写了个后台页面
在web文件夹下面创建一个包,在这个包下面创建management.jsp写个初步的后台页面,另外在web文件夹下面写一个login.jsp登陆页面,这样才会有页面的显示。
management.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>西蒙后台管理</title>
</head>
<body>
<h3>尚在建设中</h3>
</body>
</html>
login.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>用户登录</title>
</head>
<body>
<h3>正在建设中</h3>
</body>
</html>
管理员登陆成功,现在测试普通用户登陆
报404错误是因为没有写这个前台页面,我们可以在后台看我们的普通用户登陆是成功了的