public class LoginServlet extends HttpServlet{ private final String SUCCESS_VIEW = "MyJsp.jsp"; private final String ERROR_VIEW = "index.jsp"; private UsersDao userDao = new UsersDao(); private BaseDao basedao = new BaseDao(); protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{ //1.防止乱码 request.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); //2.获取页面信息 String username = request.getParameter("username"); String password = request.getParameter("password"); //3.获取登录用户信息 request . getSession().setAttribute ( "UserName" , username ) ; request.getSession().setAttribute("password", password); Connection con=null; //4.验证操作,将用户信息封装到currentUser try { Users user = new Users(username,password); con = basedao.getConnection(); Users currentUser = userDao.login(con, user); if (null == currentUser) { //5.输入信息错误 request.setAttribute("error", "用户名或密码错误"); request.setAttribute("userName", username); request.setAttribute("password", password); RequestDispatcher dispatcher = request.getRequestDispatcher(ERROR_VIEW); dispatcher.forward(request, response); }else { //6.输入正确的信息 HttpSession session = request.getSession(); session.setAttribute("currentUser",currentUser); response.sendRedirect(SUCCESS_VIEW ); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } LoginServlet
<body> <h1>登录</h1> <form action="textServlet" method="post"> 用户名:<input type="text" name="username" value="${username}" /><br/> 密 码:<input type="password" name="password" value=""/><br/> <input type="submit" value="登录"/> <a href="regist.jsp">注册</a> </form> <font color="red">${error}</font> </body>
<% String userName = ( String ) session. getAttribute ( "UserName" ) ; %> <div align = center> 欢迎登陆 用户:<%=userName%>