javaWeb之Cookie的应用 (实现记住密码功能)

一、导入相应的jar包
mysql-connector-java-5.1.46-bin.jar
二、数据库截图
在这里插入图片描述
三、代码实现
(1)配置文件的编写
连接数据库的jdbc.properties文件

user=root
password = 123456
driverClass = com.mysql.jdbc.Driver
url = jdbc:mysql://localhost:3306/mvcproject

(2)、视图层
index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<form  id="userForm" action = "<%=request.getContextPath()%>//UserController" method="post">
			用户名<input  id = "username" type="text" name ="username" ><br><br>
			密   码<input type="password" name ="userpass" ><br><br>
			<input type="radio" value="1" name = "remmber"/>记住密码
			
			<br><br>
			<input type= "submit" value="登录"/>
		</form>
</body>
</html>

welcome.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
欢迎进入页面
</body>
</html>

(3)工具类
连接数据库的

package bzu.cn.cookieProject.utils;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;



public class Dbutils {
	static private String user= null;
	static private String password= null;
	static private String url= null;
	static private Connection conn = null;
	static private PreparedStatement pstate = null;
	static private ResultSet rs = null;
	static private String driverClass = null;
	public static Connection getConnection() throws IOException, ClassNotFoundException, SQLException {
		//获取properties对象,来接收.properties文件
		Properties pro = new Properties();
		InputStream in = Dbutils.class.getClassLoader().getResourceAsStream("jdbc.properties");
		pro.load(in);
		//获的到perproties中的信息
		user = pro.getProperty("user");
		password = pro.getProperty("password");
		url = pro.getProperty("url");
		driverClass = pro.getProperty("driverClass");
		Class.forName(driverClass);
		conn = DriverManager.getConnection(url,user,password);
		
		return conn;
	}
	public static void closeAll() {
		if(conn!=null) {
			try {
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if(pstate!=null) {
			try {
				pstate.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if(rs!=null) {
			try {
				rs.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}

设置Cookie的类

package bzu.cn.cookieProject.utils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieUtils {
	public static void getCookie(HttpServletResponse response,HttpServletRequest request,String value,int sec) {
		Cookie nameCookie = new Cookie("userName",value);
		Cookie passCookie = new Cookie("userPass",value);
		nameCookie.setMaxAge(sec);
		passCookie.setMaxAge(sec);
		response.addCookie(nameCookie);
		response.addCookie(passCookie);
		
	}
}

(4)dao层的代码
BaseDao接口

package bzu.cn.cookieProject.dao;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import bzu.cn.cookieProject.entity.User;
import bzu.cn.cookieProject.utils.Dbutils;


//查询的方法,复习,顺便巩固一下cookie
public class BaseDao {
	public User get(String sql ,Object...args) {
		Connection conn = null;
		PreparedStatement pstate = null;
		ResultSet rs = null;
		User user= null;
		try {
			conn = Dbutils.getConnection();
			pstate = conn.prepareStatement(sql);
			for(int i=0;i<args.length;i++) {
				pstate.setObject(i+1, args[i]);
			}
			rs = pstate.executeQuery();
			if(rs.next()) {
				user = new User();
				user.setId(rs.getInt("id"));
				user.setUserName(rs.getString("userName"));
				user.setUserPass(rs.getString("userPass"));
			}
		} catch (ClassNotFoundException | IOException | SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			Dbutils.closeAll();
		}
		return user;
	}
}

Usedao

package bzu.cn.cookieProject.dao;

import bzu.cn.cookieProject.entity.User;

public class UserDao {
	public User select(String name,String pass) {
		BaseDao bd  = new BaseDao();
		User user = null;
		String sql = "select userName,userPass from user where userName = ? and userPass=?";
		user = bd.get(sql,name,pass);
		return user;
	}
}

(5)控制层

package bzu.cn.cookieProject.controller;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import bzu.cn.cookieProject.dao.UserDao;
import bzu.cn.cookieProject.entity.User;
import bzu.cn.cookieProject.utils.CookieUtils;


@WebServlet("/UserController")
public class UserController extends HttpServlet {
	private static final long serialVersionUID = 1L;
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		UserDao userdao = new UserDao();
		String name = request.getParameter("username");
		String pass = request.getParameter("userpass");
		String remmber =request.getParameter("remmber");
		User user = userdao.select(name, pass);
		Cookie[] cookie = request.getCookies();
		boolean login = false;
		String acount = null;
		String password = null;
		if(cookie!=null&&cookie.length>0) {
			for(Cookie c : cookie) {
				if(c.getName().equals("userName")) {
					acount = c.getValue();
				}
				if(c.getName().equals("userPass")) {
					password = c.getValue();
				}
			}
		}
		System.out.println(acount+"**"+password);
		
		if(acount !=null && password!=null) {
			login = true;
		}
		System.out.println(login);
		//判断是否登录过
		if(!login) {
			if(user!=null) {
				if(remmber.equals("1")) {
					//调用CookieUtils类中的添加cookie的方法
					CookieUtils.getCookie(response, request, name, 24*60*60);
					CookieUtils.getCookie(response, request, pass, 24*60*60);
				}
				
				System.out.println(user);
				response.sendRedirect(request.getContextPath()+"/welcome.jsp");
			}else {
				response.getWriter().write("登录失败");
				response.sendRedirect(request.getContextPath()+"/index.jsp");
			}
		}else {
			System.out.println("已经记住密码");
			response.sendRedirect(request.getContextPath()+"/welcome.jsp");
		}
		
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		doGet(request, response);
	}

}

(6)实体类 User

public class User {
	private int id;
	private String userName;
	private String userPass;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public String getUserPass() {
		return userPass;
	}
	public void setUserPass(String userPass) {
		this.userPass = userPass;
	}
	public User(int id, String userName, String userPass) {
		super();
		this.id = id;
		this.userName = userName;
		this.userPass = userPass;
	}
	public User() {
		super();
		// TODO Auto-generated constructor stub
	}
	@Override
	public String toString() {
		return "User [id=" + id + ", userName=" + userName + ", userPass=" + userPass + "]";
	}
	
}

Cookie的基础知识请看这篇博客javaWeb之Cookie概述

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
JavaWeb登录记住密码功能可以通过Cookie实现,具体步骤如下: 1. 在登录时,判断用户是否勾选了“记住密码”选项,如果勾选了,则将用户名和密码保存到Cookie中。 2. 在登录成功后,判断是否勾选了“记住密码”选项,如果勾选了,则将用户名和密码保存到Cookie中。 3. 在用户下次登录时,先判断Cookie中是否保存了用户名和密码,如果有,则将其自动填充到登录表单中。 4. 如果用户手动退出登录,则需要删除保存在Cookie中的用户名和密码信息。 这里提供一个简单的示例代码: ```java //保存Cookie Cookie usernameCookie = new Cookie("username", username); usernameCookie.setMaxAge(7 * 24 * 60 * 60); //设置Cookie有效期为7天 response.addCookie(usernameCookie); Cookie passwordCookie = new Cookie("password", password); passwordCookie.setMaxAge(7 * 24 * 60 * 60); //设置Cookie有效期为7天 response.addCookie(passwordCookie); //读取Cookie Cookie[] cookies = request.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { if ("username".equals(cookie.getName())) { String username = cookie.getValue(); //将用户名填充到登录表单中 } if ("password".equals(cookie.getName())) { String password = cookie.getValue(); //将密码填充到登录表单中 } } } //删除Cookie Cookie usernameCookie = new Cookie("username", null); usernameCookie.setMaxAge(0); response.addCookie(usernameCookie); Cookie passwordCookie = new Cookie("password", null); passwordCookie.setMaxAge(0); response.addCookie(passwordCookie); ``` 需要注意的是,为了保障安全,保存在Cookie中的密码应该进行加密处理。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值