关于HTML和JSP登陆界面验证码的问题

html-css014

关于HTML和JSP登陆界面验证码的问题,第1张

验证码原理:验证码即为你应用中的一个servlet地址,该地址的响应是一个图片输出流,把你生成的验证码以图片的形式响应给页面即可,下面是一个生成验证码的代码,参考:

package com.ec.common.util

import java.awt.Color

import java.awt.Font

import java.awt.Graphics

import java.awt.image.BufferedImage

import java.io.IOException

import java.util.Random

import javax.imageio.ImageIO

import javax.servlet.http.HttpServletRequest

import javax.servlet.http.HttpServletResponse

import javax.servlet.http.HttpSession

public class VerificationCodeUtil {

//设置字母的大小,大小

private static Font mFont = new Font("Times New Roman", Font.BOLD, 20)

static Color getRandColor(int fc,int bc) {

Random random = new Random()

if(fc>255) fc=255

if(bc>255) bc=255

int r=fc+random.nextInt(bc-fc)

int g=fc+random.nextInt(bc-fc)

int b=fc+random.nextInt(bc-fc)

return new Color(r,g,b)

}

/**

* <p>方法名称: generateImage|描述: 生成验证码</p>

* @param request

* @param response

* @param codeName 验证码session中的属性名称

* @param width 验证码宽度-不能小于60px

* @param height 验证码高度-不能小于20px

* @throws IOException

*/

public static void generateImage(HttpServletRequest request, HttpServletResponse response,String codeName,int width,int height) throws IOException {

response.setHeader("Pragma","No-cache")

response.setHeader("Cache-Control","no-cache")

response.setDateHeader("Expires", 0)

//表明生成的响应是图片

response.setContentType("image/jpeg")

BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB)

Graphics g = image.getGraphics()

Random random = new Random()

g.setColor(getRandColor(200,250))

g.fillRect(1, 1, width-1, height-1)

g.setColor(new Color(102,102,102))

g.drawRect(0, 0, width-1, height-1)

g.setFont(mFont)

g.setColor(getRandColor(160,200))

//画随机线

for (int i=0i<155i++) {

int x = random.nextInt(width - 1)

int y = random.nextInt(height - 1)

int xl = random.nextInt(6) + 1

int yl = random.nextInt(12) + 1

g.drawLine(x,y,x + xl,y + yl)

}

//从另一方向画随机线

for (int i = 0i < 70i++) {

int x = random.nextInt(width - 1)

int y = random.nextInt(height - 1)

int xl = random.nextInt(12) + 1

int yl = random.nextInt(6) + 1

g.drawLine(x,y,x - xl,y - yl)

}

//生成随机数,并将随机数字转换为字母

String sRand=""

for (int i=0i<4i++) {

int itmp = random.nextInt(26) + 65

char ctmp = (char)itmp

sRand += String.valueOf(ctmp)

g.setColor(new Color(20+random.nextInt(110),20+random.nextInt(110),20+random.nextInt(110)))

g.drawString(String.valueOf(ctmp),15*i+((width-60)/3),random.nextInt(height-20)+20)

}

HttpSession session = request.getSession(true)

session.setAttribute(codeName,sRand)

g.dispose()

ImageIO.write(image, "JPEG", response.getOutputStream())

}

}

在html中的文本框中加入验证码,可以通过以下代码实现:

验证码通过GD生成PNG图片,并把$randval随机数字赋给

在通过用户输入的$_POST进行比较,来判断是否正确。达到需要实现的功能,需要修改php.ini文件,使php支持GD库。

在文本框中加入验证码?

还是用一段代码生成验证码图片然后在html页面中显示出来?如果是后者可以帮你解决一下