Servlet实现一个简单的登录[验证码]功能

开发工具
主要用的开发工具为 MyEclipse(2014、2016均可)、Tomcat 6.0以上、浏览器等。

开发环境
开发环境为windows系统,已安装配置Java最新版开发环境。

主要功能与语言
登录验证码。

所采用JSP+Servlet+JavaBean传统方式,仅限于学习使用。

主要代码实现
ValidateServlet.java(实现的功能:随机生成验证码)

ValidateServlet.java
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public classValidateServletextends HttpServlet {
// 验证吗图片的宽度
private int width = 200;;
// 高度
private int height = 80;
// 验证吗的字符个数
private int codeCount = 4;
private int x = 0;
// 字体高度
private int fontHeight;
private int codeY;
char[] codeSequence = { ‘A’, ‘B’, ‘C’, ‘D’, ‘E’, ‘F’, ‘G’, ‘H’, ‘I’, ‘J’,
‘K’, ‘L’, ‘M’, ‘N’, ‘O’, ‘P’, ‘Q’, ‘R’, ‘S’, ‘T’, ‘U’, ‘V’, ‘W’,
‘X’, ‘Y’, ‘Z’, ‘0’, ‘1’, ‘2’, ‘3’, ‘4’, ‘5’, ‘6’, ‘7’, ‘8’, ‘9’ };
@Override
public void init() throws ServletException {
super.init();
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 创建一个随机数生成器类
Random random = new Random();
// 1、生成一幅图片。
x = width / (codeCount + 1);
fontHeight = height - 2;
codeY = height - 4;
// 定义图像buffer
BufferedImage buffImg = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
Graphics2D g = buffImg.createGraphics();
// 将图像填充为白色
g.setColor(Color.WHITE);
g.fillRect(0, 0, width, height);
// 创建字体,字体的大小应该根据图片的高度来定。
Font font = new Font(“Fixedsys”, Font.PLAIN, fontHeight);
// 设置字体。
g.setFont(font);
// 画边框。
g.setColor(Color.BLACK);
g.drawRect(0, 0, width - 1, height - 1);
// 随机产生160条干扰线,使图象中的认证码不易被其它程序探测到。
g.setColor(Color.BLACK);
for (int i = 0; i < 160; i++) {
int x = random.nextInt(width);
int y = random.nextInt(height);
int xl = random.nextInt(12);
int yl = random.nextInt(12);
g.drawLine(x, y, x + xl, y + yl);
}
// 2、生产随机数
// randomCode用于保存随机产生的验证码,以便用户登录后进行验证。
StringBuffer randomCode = new StringBuffer();
int red = 0, green = 0, blue = 0;
// 随机产生codeCount数字的验证码。
for (int i = 0; i < codeCount; i++) {
// 得到随机产生的验证码数字。
String strRand = String.valueOf(codeSequence[random.nextInt(36)]);
// 产生随机的颜色分量来构造颜色值,这样输出的每位数字的颜色值都将不同。
red = random.nextInt(255);
green = random.nextInt(255);
blue = random.nextInt(255);
// 用随机产生的颜色将验证码绘制到图像中。
g.setColor(new Color(red, green, blue));
g.drawString(strRand, (i + 1) * x, codeY);
// 将产生的四个随机数组合在一起。
randomCode.append(strRand);
}
// 3、要把随机数放在session中
// 将四位数字的验证码保存到Session中。
HttpSession session = request.getSession();
session.setAttribute(“validateCode”, randomCode.toString());
// 4、输出图片
// 禁止图像缓存。
response.setHeader(“Pragma”, “no-cache”);
response.setHeader(“Cache-Control”, “no-cache”);
response.setDateHeader(“Expires”, 0);
response.setContentType(“image/jpeg”);
// 将图像输出到Servlet输出流中。
ServletOutputStream out = response.getOutputStream();
ImageIO.write(buffImg, “jpeg”, out);
out.flush();
out.close();
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
LoginServlet.java(实现的功能:实现登录功能)
// 首先是先判断用户输入的验证是否正确
// 然后再判断用户输入的账号密码是否正确
这里我没有根据数据库去查询 !只是做了个简单的测试 !判断用户输入的账号只能为:java,密码:123
如果正确则登录成功然后跳转到LoginSuccess.jsp页面!否则登录失败留在原来的页面!
LoginServlet.java
import java.io.IOException;
import java.net.URLEncoder;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public classLoginServletextends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// 首先是先判断用户输入的验证是否正确
// 然后再判断用户输入的账号密码是否正确
HttpSession session = req.getSession();
// 获取服务器生成的验证码
String ServiceCode = session.getAttribute(“validateCode”).toString();
// 获取用户输入的的验证码
String ClientCode = req.getParameter(“codetext”);
// 验证用户输入的验证码与服务器生产的验证码是否一样
if (ClientCode.equalsIgnoreCase(ServiceCode)) {
// 获取用户输入的的账号
String username = req.getParameter(“username”);
// 获取用户输入的的密码
String password = req.getParameter(“password”);
// 这里我没有根据数据库去查询 !只是做了个简单的测试 !判断用户输入的账号只能为:java,密码:123
// 如果正确则登录成功!否则登录失败
if (username.equals(“java”) && password.equals(“123”)) {
// 登录成功之后跳转到LoginSuccess.jsp页面!并且在页面显示username的值
req.setAttribute(“username”, username);
req.getRequestDispatcher(“LoginSuccess.jsp”).forward(req, resp);
} else {
String erro = “你输入的账号密码错误!请重新输入!”;
erro = URLEncoder.encode(erro, “utf-8”);
resp.sendRedirect(“index.jsp?erro=” + erro);
}
} else {
String erro = “你输入的验证码错误!请重新输入!”;
erro = URLEncoder.encode(erro, “utf-8”);
resp.sendRedirect(“index.jsp?erro=” + erro);
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doGet(req, resp);
}

}
web.xml(关联servlet)
web.xml

<?xml version="1.0" encoding="UTF-8"?>




LoginServlet
com.servlet.LoginServlet


LoginServlet
/LoginServlet

ValidateServlet com.servlet.ValidateServlet ValidateServlet /ValidateServlet index.jsp index.jsp(登录界面) index.jsp <%@ page language="java" import="java.util.*" pageEncoding="Utf-8"%> <%@page import="java.net.URLDecoder"%> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; %> My JSP 'index.jsp' starting page <% String erro=request.getParameter("erro");

if(erro!=null){
erro=new String(erro.getBytes(“ISO-8859-1”),“utf-8”);
erro=URLDecoder.decode(erro, “utf-8”);
}else{
erro="";
}
%>
<%=erro %>























用户名:
密码:
验证码: 看不清,换一张

LoginSuccess.jsp(用户登录成功之后跳到这个页面)
LoginSuccess.jsp
<%@ page language=“java” import=“java.util.*” pageEncoding=“UTF-8”%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"?/"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

My JSP 'LoginSuccess.jsp' starting page 恭喜用户:${username} 成功登录!
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以通过在Servlet中添加一个验证码生成和验证的功能实现输入验证码功能。具体步骤如下: 1. 在Servlet中生成验证码图片和验证码字符串,可以使用第三方库Kaptcha,通过以下代码实现: ```java // 生成验证码图片和验证码字符串 String code = (String) request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY); BufferedImage image = new BufferedImage(200, 50, BufferedImage.TYPE_INT_RGB); Graphics2D g = (Graphics2D) image.getGraphics(); g.setColor(Color.WHITE); g.fillRect(0, 0, 200, 50); g.setColor(Color.BLACK); g.setFont(new Font("Arial", Font.BOLD, 30)); g.drawString(code, 50, 35); ImageIO.write(image, "JPEG", response.getOutputStream()); ``` 2. 在前端页面中显示验证码图片,可以通过以下代码实现: ```html <img src="captcha" alt="验证码"> ``` 其中,"captcha"是Servlet的请求路径。 3. 在前端页面中添加一个输入框,用于输入验证码: ```html <input type="text" name="captcha" placeholder="请输入验证码"> ``` 4. 在Servlet中获取用户输入的验证码,并进行验证: ```java // 获取用户输入的验证码 String captcha = request.getParameter("captcha"); // 获取生成的验证码字符串 String code = (String) request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY); // 进行验证码验证 if (captcha == null || !captcha.equalsIgnoreCase(code)) { // 验证码错误,返回错误信息 response.getWriter().write("验证码错误"); return; } ``` 其中,Constants.KAPTCHA_SESSION_KEY是Kaptcha中存储验证码字符串的Session Key。 这样,就可以通过Servlet实现输入验证码功能了。注意,这里的验证码验证只是简单的比较用户输入的验证码和生成的验证码字符串是否相等,为了增加安全性,你可以通过加密等方式对验证码进行更复杂的验证。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值