Servlet实现网页十天免登陆功能
前言
我们在登录网页的时候有时候会见到有几个字叫十天内免登陆复选框,比如126邮箱的登录页面
实现:
这里我们就要使用Cookie技术,Cookie技术是Web开发中必备的技术之一。
先开看下我的项目结构,下面直接贴代码,代码里面有详细的注释。
登录页面index.html
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <!--login指向的是配置文件--> <form action="/你的项目名/login" method="post"> 账号 <input type="text" name="username"><br> 密码 <input type="password" name="password"><br> <input type="checkbox" name="tenDayLogin" value="ok">十天内免登陆<br> 登录 <input type="submit" value="登录"> </form> </body> </html>
配置文件web.xml
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>项目名</display-name> <welcome-file-list> <!-- 将验证cookie的Servlet作为登录页面。验证成功就不需要再跳转到登录页面了 --> <welcome-file>islogin</welcome-file> </welcome-file-list> <servlet> <servlet-name>login</servlet-name> <servlet-class>com.zhixi.zhang.LoginServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>login</servlet-name> <url-pattern>/login</url-pattern> </servlet-mapping> <servlet> <servlet-name>islogin</servlet-name> <servlet-class>com.zhixi.zhang.CheckLoginServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>islogin</servlet-name> <url-pattern>/islogin</url-pattern> </servlet-mapping> </web-app>
SQL文件,用于存储用户的账号跟密码
drop table if exists t_user; create table t_user( id int(10) primary key auto_increment, username varchar(32) not null unique, password varchar(32) not null, realname varchar(128) ); insert into t_user(username,password,realname) values('zhangzhixi','zhixi158','root'); insert into t_user(username,password,realname) values('zhangsan','123','普通用户'); select * from t_user;
验证Cookie类
package com.zhixi.zhang; import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class CheckLoginServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); //从request中获取所有的cookie Cookie[] cookies = request.getCookies(); String username = null; String password = null;; if(cookies != null) { //遍历cookie for(Cookie cookie : cookies) { if("username".equals(cookie.getName())) {//看cookie的name是不是与cookie的名字匹配 username = cookie.getValue(); }else if("password".equals(cookie.getName())){ password = cookie.getValue(); } } } if(username != null && password != null) {// //连接JDBC数据库验证用户名跟密码 Connection conn =null; PreparedStatement ps = null; ResultSet rs = null; boolean login = false;//判断是否登录成功 String realName = null;//用户 try { Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/donglijiedian","root","zhixi158"); String sql = "select * from t_user where username=? and password=?"; ps = conn.prepareStatement(sql); ps.setString(1, username); ps.setString(2, password); rs = ps.executeQuery(); if(rs.next()) { login = true; realName = rs.getString("realname"); } }catch(Exception e) { e.printStackTrace(); }finally { if(rs != null) { try { rs.close(); } catch (SQLException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } } if(ps != null) { try { ps.close(); } catch (SQLException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } } if(conn != null) { try { conn.close(); } catch (SQLException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } } } //跳转页面 if(login) {//登录成功 out.print("欢迎"+ realName +"登录成功!"); }else {//登录失败 out.print("登录失败,请检查用户名或者密码!"); } }else {//cookie验证失败,跳转到登录页面 response.sendRedirect(request.getContextPath()+"/index.html"); } } }
登录类
package com.zhixi.zhang; import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class LoginServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /** 思路: 获取用户名和密码 JDBC连接数据库验证用户名和密码 登录成功跳转到成功页面 登录成功后查看用户是否勾选了十天内免登陆 检查cookie,验证十天内有没有更改过密码,然后直接跳转到成功页面 登录失败跳转到失败页面 */ //1、解决乱码 request.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); //2、获取用户输入的用户名和密码 PrintWriter out = response.getWriter(); String username = request.getParameter("username"); String password = request.getParameter("password"); Connection conn =null; PreparedStatement ps = null; ResultSet rs = null; boolean login = false;//判断是否登录成功 String realName = null;//用户 try { Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/donglijiedian","root","zhixi158"); String sql = "select * from t_user where username=? and password=?"; ps = conn.prepareStatement(sql); ps.setString(1, username); ps.setString(2, password); rs = ps.executeQuery(); if(rs.next()) { login = true; realName = rs.getString("realname"); } }catch(Exception e) { e.printStackTrace(); }finally { if(rs != null) { try { rs.close(); } catch (SQLException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } } if(ps != null) { try { ps.close(); } catch (SQLException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } } if(conn != null) { try { conn.close(); } catch (SQLException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } } } //跳转页面 if(login) {//登录成功 out.print("欢迎"+ realName +"登录成功!"); //通过name获取value String parameter = request.getParameter("tenDayLogin"); if("ok".equals(parameter)) {//说明用户选择了十天内免登陆 //创建Cookie对象 Cookie cookie1 = new Cookie("username",username); Cookie cookie2 = new Cookie("password",password); //设置有效时间 cookie1.setMaxAge(60 * 60 * 24 * 10); cookie2.setMaxAge(60 * 60 * 24 * 10); //设置关联路径,默认根路径就行 cookie1.setPath(request.getContextPath()); cookie2.setPath(request.getContextPath()); //发送Cookie给浏览器 response.addCookie(cookie1); response.addCookie(cookie2); } }else {//登录失败 out.print("登录失败,请检查用户名或者密码!"); } } }
测试
未勾选十天免登陆
勾选十天内免登陆
1、先使用账号密码登录并勾选十天内免登陆登录登录
2、关闭浏览器再进行访问地址
这次是我直接重新开启服务器跳转的页面,因为设置了Cookie的实效时长,在硬盘中实际上是已经存储了我的账号跟密码了。所以直接就进入到了成功登录的页面了!