使用cookie(实现免密登录)

1. 需求

用户访问登录页面,输入用户名和密码后,点击登录。登录成功,则跳转到主页面,登录失败则跳转到登录页面,并在页面中显示错误提示语。

用户在登录页面中选择记住用户名和密码,则登录成功后,以后再次登录的时候就不需要输入用户名和密码了,点击登录按钮直接访问主页面。

2. 技术要求

使用Servlet+Cookie+Jdbc+MySQL完成!

3. 数据库设计

新建数据库,库名为XXX,并创建XXX表。

表名:T_USER
字段名 类型 约束
id int 主键
username varchar(100)
password varchar(20)

4. 环境搭建

4.1 创建Java Enterprise项目

使用cookie(实现免密登录)_第1张图片

4.2 导入相关jar包

在WEB-INF包下创建lib并添加(有德鲁伊jar包,操作数据库的jar包)

4.3 创建包结构

使用cookie(实现免密登录)_第2张图片

4.4 编写pojo实体类
public class User {
    private Integer id;
    private String username;
    private String password;

    public User() {
    }

    public User(Integer id, String username, String password) {
        this.id = id;
        this.username = username;
        this.password = password;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}
4.5 编写数据库工具类
public class Fengconnectionpool {

   public static DruidDataSource dataSource=null;

    static{
        //1.获取数据源
        dataSource = new DruidDataSource();
        //1.2 基本4项
        //  1) 驱动
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        //  2) 连接
        dataSource.setUrl("jdbc:mysql://localhost:3306/javaweblogin?useSSL=false&characterEncoding=utf-8&serverTimezone=Asia/Shanghai");
        //  3) 用户
        dataSource.setUsername("root");
        //  4) 密码
        dataSource.setPassword("123456");
        //1.3 特殊项【可选】
        // 1) 初始化大小
        dataSource.setInitialSize(5);
        // 2) 最大值活动数
        dataSource.setMaxActive(10);
        // 3) 最小空闲数
        dataSource.setMinIdle(2);
    }
     //将获得连接也封装进一个方法,写成静态以后直接类名调用
    public static Connection getConnection() {
        try {
            //2.获得连接
            DruidPooledConnection conn = dataSource.getConnection();
            return conn;
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }
    //将资源的释放也封装进方法中
    public  static  void close(PreparedStatement ps,Connection connection){
        if (ps !=null){
            try {
                ps.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (connection !=null){
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }


}

 

4.6 编写dao层接口及实现类

 

public interface UserDao {
    User getUserBy(String username,String password);

}
public class UserDaoImpl implements UserDao{
    @Override
    public User getUserBy(String username, String password) {
        Connection connection=null;
        PreparedStatement ps=null;
        User user=null;
        try {
             connection = Fengconnectionpool.getConnection();
            String sql="select * from login1 where username=? and password=?";
            ps = connection.prepareStatement(sql);
            ps.setString(1,username);
            ps.setString(2,password);
            ResultSet resultSet = ps.executeQuery();
            while (resultSet.next()) {
                int id = resultSet.getInt("id");
                String username1 = resultSet.getString("username");
                String password1 = resultSet.getString("password");
                user = new User(id, username1, password1);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            Fengconnectionpool.close(ps,connection);
        }

        return user;
    }
}

4.7 编写service层接口及实现类

public interface UserService {
    User login(String username,String password);
}

 

public class UserServiceImpl implements UserService {
    private UserDao userDao=new UserDaoImpl();
    @Override
    public User login(String username, String password) {
        return userDao.getUserBy(username,password);
    }
}

5. 登录页面实现(记住密码)

@WebServlet("/loginPage")
public class LoginPageServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        resp.setContentType("text/html;charset=utf-8");
        PrintWriter writer = resp.getWriter();





        if(req.getAttribute("msg") != null){
            writer.write(""+req.getAttribute("msg")+"");
        }
        writer.write("
"); // 上次登录成功后,再次登录免密的页面 String username = ""; String password = ""; String isRemember = ""; //拿到浏览器中存储的cookie Cookie[] cookies = req.getCookies(); if(cookies != null){ for (Cookie cookie : cookies) { if(cookie.getName().equals("username")){ username = cookie.getValue(); } if(cookie.getName().equals("password")){ password = cookie.getValue(); } } } if(!username.equals("") && !password.equals("")){ isRemember = "1"; } writer.write("账号:
"); writer.write("密码:
"); if(isRemember.equals("1")){ writer.write("记住密码:
"); }else{ writer.write("记住密码:
"); } writer.write("
"); writer.write("
"); writer.write(""); writer.write(""); } }

6. 主页面功能实现

@WebServlet("/main")
public class MainServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter writer = resp.getWriter();

        writer.write("");
        writer.write("");
        writer.write("");
        writer.write("欢迎使用系统");
        writer.write("");
        writer.write("");
        writer.write("

登录成功!!
欢迎使用大佬登录系统



"); writer.write(""); writer.write(""); } }

7. 登录功能实现

@WebServlet("/log")
public class LoginServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //拿到请求页面提交的值,根据name属性拿到value值
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String isRemember = req.getParameter("isRemember");


        try {
            UserService userService = new UserServiceImpl();
            User user = userService.login(username, password);

            if(user != null){
                //登录成功后,若勾选了记住密码,那么我们就创建cookie
                if("1".equals(isRemember)){
                    Cookie cookie = new Cookie("username", username);
                    Cookie cookie2 = new Cookie("password", password);

                    cookie.setMaxAge(60*60*24*7);
                    cookie2.setMaxAge(60*60*24*7);

                    resp.addCookie(cookie);
                    resp.addCookie(cookie2);
                }else{
                    //下一次请求来时,没有勾选,获取请求对象存在的cookie,让cookie立即死亡
                    Cookie[] cookies = req.getCookies();
                    if(cookies != null){
                        for (Cookie cookie : cookies) {
                            if(cookie.getName().equals("username") || cookie.getName().equals("password")){
                                cookie.setMaxAge(0);
                                resp.addCookie(cookie);
                            }
                        }
                    }
                }
                //登录成功后重定向的页面
                resp.sendRedirect(req.getContextPath()+"/main");

            }else{
                //登陆失败请求转发回到登录页面(带着登陆失败设置的数据)
                req.setAttribute("msg", "用户名或密码错误!");
                req.getRequestDispatcher("/loginPage").forward(req, resp);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}

你可能感兴趣的:(tomcat,数据库,java,服务器,sql)