之前想做一个随机验证码的功能,自己也搜索了一下别人写的代码,然后自己重新用struts2实现了一下,现在将我自己实现代码贴出来!大家有什么意见都可以指出来!

首先是生成随机验证码图片的action:

CreateImageAction:

package com.xiaoluo.action;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.Random; import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession; import org.apache.struts2.ServletActionContext; import com.opensymphony.xwork2.ActionSupport; public class CreateImageAction extends ActionSupport
{
private ByteArrayInputStream inputStream; private static int WIDTH = 60; private static int HEIGHT = 20; public ByteArrayInputStream getInputStream()
{
return inputStream;
} public void setInputStream(ByteArrayInputStream inputStream)
{
this.inputStream = inputStream;
}
private static String createRandom()
{
String str = "0123456789qwertyuiopasdfghjklzxcvbnm"; char[] rands = new char[4]; Random random = new Random(); for (int i = 0; i < 4; i++)
{
rands[i] = str.charAt(random.nextInt(36));
} return new String(rands);
} private void drawBackground(Graphics g)
{
// 画背景
g.setColor(new Color(0xDCDCDC)); g.fillRect(0, 0, WIDTH, HEIGHT); // 随机产生 120 个干扰点 for (int i = 0; i < 120; i++)
{
int x = (int) (Math.random() * WIDTH); int y = (int) (Math.random() * HEIGHT); int red = (int) (Math.random() * 255); int green = (int) (Math.random() * 255); int blue = (int) (Math.random() * 255); g.setColor(new Color(red, green, blue)); g.drawOval(x, y, 1, 0);
}
} private void drawRands(Graphics g, String rands)
{
g.setColor(Color.BLACK); g.setFont(new Font(null, Font.ITALIC | Font.BOLD, 18)); // 在不同的高度上输出验证码的每个字符 g.drawString("" + rands.charAt(0), 1, 17); g.drawString("" + rands.charAt(1), 16, 15); g.drawString("" + rands.charAt(2), 31, 18); g.drawString("" + rands.charAt(3), 46, 16); System.out.println(rands); } @Override
public String execute() throws Exception
{
HttpServletResponse response = ServletActionContext.getResponse(); // 设置浏览器不要缓存此图片
response.setHeader("Pragma", "no-cache"); response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expires", 0); String rands = createRandom(); BufferedImage image = new BufferedImage(WIDTH, HEIGHT,
BufferedImage.TYPE_INT_RGB); Graphics g = image.getGraphics(); // 产生图像
drawBackground(g); drawRands(g, rands); // 结束图像 的绘制 过程, 完成图像
g.dispose(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ImageIO.write(image, "jpeg", outputStream); ByteArrayInputStream input = new ByteArrayInputStream(outputStream
.toByteArray()); this.setInputStream(input); HttpSession session = ServletActionContext.getRequest().getSession(); session.setAttribute("checkCode", rands); input.close(); outputStream.close(); return SUCCESS;
}
}

以上是生成随机验证码图片的action,将生成的随机数放到session里,然后页面提交到验证随机数的action:

LoginValidateAction:

package com.xiaoluo.action;

import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class LoginValidateAction extends ActionSupport
{
private String checkCode; public String getCheckCode()
{
return checkCode;
} public void setCheckCode(String checkCode)
{
this.checkCode = checkCode;
} @Override
public String execute() throws Exception
{
return SUCCESS;
} @Override
public void validate()
{
HttpSession session = ServletActionContext.getRequest().getSession(); String checkCode2 = (String)session.getAttribute("checkCode"); if(!checkCode.equals(checkCode2))
{
this.addActionError("输入的验证码不正确,请重新输入!");
}
}
}

下面是struts.xml配置部分代码:

      <action name="createImageAction" class="com.xiaoluo.action.CreateImageAction">
<result name="success" type="stream">
<param name="contentType">image/jpeg</param>
<param name="inputName">inputStream</param>
</result>
       </action> <action name="loginValidateAction" class="com.xiaoluo.action.LoginValidateAction">
<result name="success">/success.jsp</result>
<result name="input">/login.jsp</result>
</action>

最后就是jsp部分的代码:

login.jsp:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%> <html>
<head>
<base href="<%=basePath%>"> <title>My JSP 'login.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> <h3><font color="blue">带有验证码的登陆界面</font></h3> <s:form action="loginValidateAction.action" theme="simple"> 用户名:<s:textfield name="username"></s:textfield><br>
密码 :<s:password name="password"></s:password><br>
验证码:<s:textfield name="checkCode"></s:textfield>
     
     <!--若要点击图片刷新,重新得到一个验证码,要在后面加上个随机数,这样保证每次提交过去的都是不一样的path,防止因为缓存而使图片不刷新-->
<img src="createImageAction.action" onclick="this.src='createImageAction.action?'+ Math.random()" title="点击图片刷新验证码"/><br>
<s:actionerror cssStyle="color:red"/> <s:submit value="提交"></s:submit> </s:form> </body>
</html>

struts---JSP界面验证码生成与验证的更多相关文章

  1. php 图片验证码生成 前后台验证

    自己从前一段时间做了个php小项目,关于生成图片验证码生成和后台的验证,把自己用到的东西总结一下,希望大家在用到相关问题的时候可以有一定的参考性. 首先,php验证码生成. 代码如下: 1.生成图像代 ...

  2. [转]php 图片验证码生成 前后台验证

    本文转自:https://www.cnblogs.com/xiaoyezi/p/3541195.html 自己从前一段时间做了个php小项目,关于生成图片验证码生成和后台的验证,把自己用到的东西总结一 ...

  3. Web后端 JAVA实现验证码生成与验证功能

    首先,写一个验证码生成帮助类,用来绘制随机字母: <span style="font-size:14px;">import java.awt.Color;  impor ...

  4. PHP 用session与gd库实现简单验证码生成与验证的类

    验证码是为了防止机器灌水给网站带来污染以及增加服务器负担而出现的.目前大大小小的网站都有验证码.今天自己实现了一个简单的验证码类.说简单是因为没有加一些干扰的弧线等等,只是将文字旋转了一下.当然,因为 ...

  5. Java生成验证码并进行验证(转)

    本文转自http://blog.csdn.net/worm0527/article/details/51030864 一.实现思路 使用BufferedImage用于在内存中存储生成的验证码图片 使用 ...

  6. PHP利用jquery生成各种验证码和Ajax验证

    PHP生成验证码图片 PHP生成验证码的原理:使用PHP的GD库,生成一张带验证码的图片,并将验证码保存在Session中.PHP 生成验证码的大致流程有: .产生一张png的图片: .为图片设置背景 ...

  7. js简单验证码的生成和验证

    如何用js生成简单验证码,并验证是否正确的方法 1.html页面如下 <div> <table border="0" cellspacing="5&qu ...

  8. 第二百七十节,Tornado框架-生成验证码图片,以及验证码结合Session验证

    Tornado框架-生成验证码图片,以及验证码结合Session验证 第一.生成验证码图片  生成验证码图片需要两个必须模块 1.python自带的random(随机模块) 2.Pillow()图像处 ...

  9. jsp实现验证码

    在web开发领域里面,验证码是一个比较常见的功能,而归根到底,验证码其实就是一组随机数,或者是一个随机算术 一.基本知识 1.为什么需要验证码? 验证码,很多时候出现在注册页面或者登陆界面,在这些页面 ...

随机推荐

  1. Tomcat配置HTTPS方式(单向)

    简要记录主要步骤备忘 1.进入到jdk下的bin目录 2.输入如下指令 keytool -v -genkey -alias tomcat -keyalg RSA -keystore d:/tomcat ...

  2. LogPolar 对数极坐标

    LogPolar 对数极坐标 cvLogPolar 对数极坐标(logpolar)是仿真生物视网膜中央凹陷的特性,具有数据压缩的能力,可用于目标跟踪中快速尺度和旋转变换不变的模板匹配. 对数极坐标其实 ...

  3. 1.0 多控制器管理(附:Demo)

    本文并非最终版本,如有更新或更正会第一时间置顶,联系方式详见文末 如果觉得本文内容过长,请前往本人 “简书”       控制器 :   一个iOS的app很少只由一个控制器组成,除非这个app极其简 ...

  4. CentOS7和win7双系统启动项

    1.添加win7启动项编辑文件 /boot/grub2/grub2.conf menuentry 'Windows 7' { insmod ntfs set root='hd0,1' chainloa ...

  5. Test Driven Development

    链接:https://msdn.microsoft.com/zh-tw/library/dn743856.aspx

  6. php正则获取html图片标签信息(采集图片)

    php获取html图片标签信息(采集图片),实现图片采集及其他功能,带代码如下: <?php $str="<img src='./a.jpg'/>111111<img ...

  7. Lua面向对象

    lua中的table就是一种对象,但是如果直接使用仍然会存在大量的问题,如下: 1 Account = {balance = 0}2 function Account.withdraw(v)3 Acc ...

  8. 【转】自学成才秘籍!机器学习&深度学习经典资料汇总

      小编都深深的震惊了,到底是谁那么好整理了那么多干货性的书籍.小编对此人表示崇高的敬意,小编不是文章的生产者,只是文章的搬运工. <Brief History of Machine Learn ...

  9. 几款不错的VisualStudio2010插件

    1.Gradient Selection 这个插件能使VisualStudio的高亮文本看起来是类似Blend的那样的效果,看起来更加舒服 2.LineAdornments 这个插件可以高亮光标所在的 ...

  10. DS实验题 融合软泥怪-2 Heap实现

    题目和STL实现:DS实验题 融合软泥怪-1 用堆实现优先队列 引言和堆的介绍摘自:Priority Queue(Heaps)--优先队列(堆) 引言: 优先队列是一个至少能够提供插入(Insert) ...