前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Servlet实现一个简单的登录【验证码】功能

Servlet实现一个简单的登录【验证码】功能

作者头像
Java学习
发布2018-04-16 11:29:39
1.7K0
发布2018-04-16 11:29:39
举报
文章被收录于专栏:java学习java学习

最新通知

●回复"每日一练"获取以前的题目!

●【新】Ajax知识点视频更新了!(回复【学习视频】获取下载链接)

●【新】HTML5知识点视频更新了!(回复【前端资料】获取下载链接)

●答案公布时间:为每期发布题目的第二天

★【新】回复“测试题”获取昨天发布的软件工程师初级阶段测试题答案

★【新】回复“学习资料”获取java学习电子文档

★【新】需要求职简历模板的可以加小编微信xxf960513

★【新】回复“聊天系统”获取java多人聊天系统项目源码!

●我希望大家积极参与答题!有什么不懂可以加小编微信进行讨论

★珍惜每一天,拼搏每一天,专心每一天,成功每一

如果你是初学者,或者是自学者!你可以加小编微信!小编可以给你建议以及给你提供学习资料!你在学习上有什么问题都可以咨询小编!小编都会为你解答!注:本公众号纯属个人公众号!不存在任何培训机构招生信息

  • 开发工具

主要用的开发工具为 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"?>

<web-app version="2.5"

xmlns="http://java.sun.com/xml/ns/javaee"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://java.sun.com/xml/ns/javaee

http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

<display-name></display-name>

<servlet>

<servlet-name>LoginServlet</servlet-name>

<servlet-class>com.servlet.LoginServlet</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>LoginServlet</servlet-name>

<url-pattern>/LoginServlet</url-pattern>

</servlet-mapping>

<servlet>

<servlet-name>ValidateServlet</servlet-name>

<servlet-class>com.servlet.ValidateServlet</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>ValidateServlet</servlet-name>

<url-pattern>/ValidateServlet</url-pattern>

</servlet-mapping>

<welcome-file-list>

<welcome-file>index.jsp</welcome-file>

</welcome-file-list>

</web-app>

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 + "/";

%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

<head>

<base href="<%=basePath%>">

<title>My JSP 'index.jsp' starting page</title>

<meta http-equiv="pragma" content="no-cache">

<meta http-equiv="cache-control" content="no-cache">

<meta http-equiv="expires" content="0">

<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">

<meta http-equiv="description" content="This is my page">

<!--

<link rel="stylesheet" type="text/css" href="styles.css">

-->

</head>

<script type="text/javascript">

//点击更新验证码

function change(){

document.getElementById("code").src="ValidateServlet?a="+new Date();

}

</script>

<body>

<span style="color: red">

<%

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 %>

</span>

<form action="LoginServlet" method="post">

<table>

<tr>

<td>用户名:</td>

<td><input type="text" name='username' style="width: 140px"></td>

<td></td>

</tr>

<tr>

<td>密码:</td>

<td><input type="password" name='password' style="width: 140px"></td>

<td></td>

</tr>

<tr>

<td>验证码:</td>

<td><input type="text" name='codetext' style="width: 70px"> <img alt="" src="ValidateServlet" width="60px"

height="25px" id='code' onclick="change()"></td>

<td><span onclick="change()">看不清,换一张</span></td>

</tr>

<tr>

<td></td>

<td><input type="submit" value="提交"> <input type="reset" value="重置"></td>

<td></td>

</tr>

</table>

</form>

</body>

</html>

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+"/";

%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

<head>

<base href="<%=basePath%>">

<title>My JSP 'LoginSuccess.jsp' starting page</title>

<meta http-equiv="pragma" content="no-cache">

<meta http-equiv="cache-control" content="no-cache">

<meta http-equiv="expires" content="0">

<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">

<meta http-equiv="description" content="This is my page">

<!--

<link rel="stylesheet" type="text/css" href="styles.css">

-->

</head>

<body>

恭喜用户:${username} 成功登录!

</body>

</html>

一张图诠释你做一个合格的程序员必备的知识点

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2017-07-19,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 java学习 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
验证码
腾讯云新一代行为验证码(Captcha),基于十道安全栅栏, 为网页、App、小程序开发者打造立体、全面的人机验证。最大程度保护注册登录、活动秒杀、点赞发帖、数据保护等各大场景下业务安全的同时,提供更精细化的用户体验。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档