WebServlet 的 login 方法
[Java] 纯文本查看 复制代码 package Servlet;
import Dao.UserDao;
import domain.User;
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 java.io.IOException;
/**
* @Author: hr947x
* @Date: 2019/1/16 14:35
* @Description: 登录服务
*/
@WebServlet("/login")
public class login extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 设置 request 编码
request.setCharacterEncoding("utf-8");
// 读取的 request 中的用户名与密码
String username = request.getParameter("username");
String password = request.getParameter("password");
// 创建 User 对象
User loginUser = new User();
loginUser.setUsername(username);
loginUser.setPassword(password);
// 创建 UserDao 对象
UserDao dao = new UserDao();
User user = dao.login(loginUser);
if (user != null) {
// 非空表示登录成功
// - 将 user 加入 request 中
request.setAttribute("user", user);
// - 将 request 转发
request.getRequestDispatcher("/success").forward(request, response);
} else {
request.setAttribute("info_", "123456222222");
request.getRequestDispatcher("/fail").forward(request, response);
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
}
|