zoukankan      html  css  js  c++  java
  • selves

    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;
    import java.sql.*;

    @WebServlet("/Login")
    public class LoginServlet extends HttpServlet {
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            doGet(req,resp);//转发到get 执行相同逻辑
        }

        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

            //获取参数
            String name = req.getParameter("username");
            String password = req.getParameter("pwd");


            String error = null; //错误信息
            boolean flag = false; //是否登陆成功
            //验证数据可靠性
            if(name == null || password == null || name.equals("") || password.equals("")){
                error="用户名和密码不能为空!";
            }else {
                //查询数据库
                try {
                    Class.forName("com.mysql.jdbc.Driver");
                    Connection connect = DriverManager.getConnection("jdbc:mysql://127.0.0.1/db1?charsetEncoding=utf-8&user=root&password=admin");
                    PreparedStatement statement = connect.prepareStatement("select *from user where name = ? and password = ?");
                    statement.setObject(1,name);
                    statement.setObject(2,password);
                    ResultSet set = statement.executeQuery();
                    if(set.next()){
                        flag = true;
                    }else{
                        error="用户名和密码错误!";
                    }
                } catch (ClassNotFoundException | SQLException e1) {
                    error = "服务器忙,请稍后再试!";
                }
            }

            if(flag){
                //删除已存在的错误信息,避免后续登录页面展示重复展示
                req.getSession().removeAttribute("error");
                //添加用户名称到session
                req.getSession().setAttribute("user",name);
                //跳转页面
                req.getRequestDispatcher("./index.jsp").forward(req,resp);
            }else{
                //添加错误信息到session
                req.getSession().setAttribute("error",error);
                //跳转页面
                req.getRequestDispatcher("./login.jsp").forward(req,resp);
            }
        }
    }
     
  • 相关阅读:
    POJ 1182 食物链(带权并查集)
    UVa 10655 n次方之和(矩阵快速幂)
    2016湘潭邀请赛—Heartstone
    2016湘潭邀请赛—Gambling
    UVa 10375 选择与除法(唯一分解定理)
    UVa 1637 纸牌游戏(全概率公式)
    POJ 2443 Set Operation(压位加速)
    UVa 11248 网络扩容(最大流(需要优化))
    51Nod 1737 配对(树的重心)
    51Nod 1070 Bash游戏 V4(斐波那契博弈)
  • 原文地址:https://www.cnblogs.com/huaobin/p/14162642.html
Copyright © 2011-2022 走看看