session实现用户验证码登录


前言

在实际开发中,为了保护用户信息的安全,都会在网站登录界面上添加一次性验证码,从而限制人们使用软件来暴力猜测密码。在实现用户登录案例中,增加一次性验证码功能。


提示:以下是本篇文章正文内容,下面案例可供参考

一、什么是Session

浏览器访问Web服务器时,服务器会为每⼀个浏览器在服务器端的内存中分配空间,单独
创建⼀个Session对象,该对象有⼀个id属性,其值唯⼀,⼀般称之为SessionId,并且服务
器会将这个SessionId(使⽤Cookie的⽅式)发送给浏览器;浏览器再次访问服务器时,会
将SessionId发送给服务器,服务器可以依据SessionId找到对应的Session对象。
Session的优缺点
1.安全(将状态保存在服务器端)
2.Session能够保存的数据类型更丰富,Cookie只能保存字符串
3.Session能够保存更多的数据,Cookie⼤约保存4K
4.Session占⽤服务器内存,如果⽤户量过⼤,会严重影响服务器的性能

二、实现步骤

1.login.jsp页面

代码如下:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="login.do" method="post">
    <h3>登录</h3>
    用户名:<input type="text" name="username"/><br><br>
    密  码:<input type="password" name="pwd"/><br><br>
    验证码:<input name="vcode"/>
    <img src="code" onclick="this.src='code?'+Math.random();"
     class="s1" title="点击更换"/><br>
    <input type="submit" value="登录"/>
  </form>
</body>
</html>

2.新建ActionServlet类

代码如下:

package web;
import java.io.IOException;
import java.io.PrintWriter;
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 javax.servlet.http.HttpSession;
public class ActionServlet extends HttpServlet {
    public ActionServlet() {
        super();
    }
	public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html; charset=utf-8" );
		PrintWriter out = response.getWriter();
		String uri = request.getRequestURI();
		String action = uri.substring(uri. lastIndexOf("/") + 1, uri. lastIndexOf("."));
		HttpSession session = request.getSession(); //创建session
		System.out.println(session.getId());
		//判断动作是否为登录
		if(action. equals("login")) {
		    String name = request.getParameter("username");
		    String pwd = request.getParameter("pwd");
		    String vcode=request.getParameter("vcode");//用户输入的验证码
		    String session_code=request.getSession().getAttribute("check_code").toString();//session中保存的
		    //用户名密码正确,这里写死了,不访问数据库了
		if(name.equals ("DC") && pwd.equals("930826")&&vcode.equals(session_code)) {
			
		    session.setAttribute("uname" , name);//在session中保存用户名
		    response.sendRedirect("index.jsp");
		}else if(vcode.equals(session_code)){
			out.print("<script language='javascript'>alert('用户或密码错误,请重新登录!');window.location.href='login.jsp';</script>");
		    }
		else {
			out.print("<script language='javascript'>alert('验证码错误,请重新输入!');window.location.href='login.jsp';</script>");
		    }
		}
	}
}

3.新建index.jsp页面

代码如下:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
  //session验证
  Object uname=session.getAttribute("uname");
  if(uname==null){
	  response.sendRedirect("login.jsp");
	  return ;
  }
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h3>首页</h3>欢迎您:<%=uname.toString() %><br>
</body>
</html>

4.新建validateCode.jsp页面

代码如下:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<style type="text/css">
.s1{cursor:pointer;}
</style>
</head>
<body>
验证码:<input name="vcode"/>
<img src="code" onclick="this.src='code?'+Math.random();"
class="s1" title="点击更换"/>
</body>
</html>

5.新建ValidateCode.java(servlet)页面

用于产生验证码图片,代码如下:

package web;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;
import javax.imageio.ImageIO;
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 javax.servlet.http.HttpSession;
public class ValidateCode extends HttpServlet {
    public ValidateCode() {
        super();
        // TODO Auto-generated constructor stub
    }
    public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//创建空白图片
    	BufferedImage image=new BufferedImage(100,30,BufferedImage.TYPE_INT_RGB);
    	//获取图片画笔
    	Graphics g=image.getGraphics();
    	Random r=new Random();
    	//设置画笔颜色
    	g.setColor(new Color(r.nextInt(255),r.nextInt(255),r.nextInt(255)));
    	//绘制矩形的背景
    	g.fillRect(0,0,100,30);
    	//提用自定义的方法,获取长度为5的字母数字组合的字符串
    	String number=getNumber(5);
    	//将验证码存入session中
    	//request.getSession().setAttribute("check_code",number);
    	HttpSession session=request.getSession();
    	session.setAttribute("check_code", number);
    	g.setColor(new Color(0,0,0));
    	g.setFont(new Font(null,Font.BOLD,24));
    	//设置字体颜色后绘制字符串
    	g.drawString(number, 5, 25);
    	//绘制8条干扰线
    	for(int i=0;i<8;i++){
        	g.setColor(new Color(r.nextInt(255),r.nextInt(255),r.nextInt(255)));
        	g.drawLine(r.nextInt(100), r.nextInt(30), r.nextInt(100), r.nextInt(30));
    	}
    	response.setContentType("image/jpg");
    	OutputStream ops=response.getOutputStream();
    	ImageIO.write(image, "jpeg", ops);
    	ops.close();
	}
	private String getNumber(int size) {
		String str="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
		String number="";
		Random r=new Random();
		for(int i=0;i<size;i++){
			number+=str.charAt(r.nextInt(str.length()));
		}
		return number;
	}
}

三、 实验结果

在这里插入图片描述

在这里插入图片描述
本文参考https://guoqianliang.blog.csdn.net/article/details/103647335?spm=1001.2101.3001.6650.4&utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7Edefault-4-103647335-blog-120398619.pc_relevant_default&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7Edefault-4-103647335-blog-120398619.pc_relevant_default&utm_relevant_index=7

  • 3
    点赞
  • 59
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值